C# 使用字符串作为变量的一部分

C# 使用字符串作为变量的一部分,c#,C#,我想使用字符串作为变量的一部分 例如,在下面的代码中,我有一个名为productLine的字符串。我想使用这个字符串中的值来创建一个变量名,并调用这个变量的属性“value”。我希望继续切换“productLine”中的值,因此继续切换调用其值方法的变量 有没有办法做到这一点,或者我需要重写代码并采取不同的方法 foreach (string productLine in productLineData) { string templateKey = "{{" + productLine

我想使用字符串作为变量的一部分

例如,在下面的代码中,我有一个名为
productLine
的字符串。我想使用这个字符串中的值来创建一个变量名,并调用这个变量的属性“value”。我希望继续切换“productLine”中的值,因此继续切换调用其值方法的变量

有没有办法做到这一点,或者我需要重写代码并采取不同的方法

foreach (string productLine in productLineData)
{
    string templateKey = "{{" + productLine + "}}";
    string templateValue = "";
    if (productRow.productLine.Value != null)
        templateValue = productRow.productLine.Value.ToString();
    productRowText = productRowText.Replace(templateKey, templateValue);
}
productRow
是一个包含我希望使用的属性的模型

编辑:


productLine
包含字符串值。例如,它首先包含
productName
。此时,我想调用
productRow.productName.Value
。下一个“productLine”包含
productPrice
。此时我想调用
productRow.productPrice.Value
。等等。

如果要寻址的变量是类(即成员)的属性,则反射将允许您使用其名称的字符串获取/设置其值。如果变量只是一个函数范围的符号(即
string myVar=“”;
),那么它在运行时不存在,无法访问。

您可以按照romain aga的建议使用反射来实现

 using System.Reflection;


    //...
    foreach (string productLine in productLineData)
    {
        string templateKey = "{{" + productLine + "}}";
        string templateValue = string.Empty;
        object value =  productRow?.GetType()?.GetProperty(productLine)?.GetValue(productRow, null);
        if (value != null)
            templateValue = value.ToString();
        productRowText = productRowText.Replace(templateKey, templateValue);
    }
    //...

这个问题目前相当混乱(可能只是一个语言问题)。是否要将字符串用作变量的一部分?您有
productLine
,它是用字符串填充的吗?您想在调用值的位置保持切换吗?你需要用其他的语言或例子来解释它。这可能只是因为我缺乏理解,但我真的不明白其他问题是如何回答我的问题的。回答得好。在调用
GetValue
:-)之前,我会添加一个测试来检查
productRow.GetType().GetProperty(productLine)
是否为空。请参见“使用新语言编辑”功能。