小编典典

字符串到变量名

c#

我有class(Customer),它拥有200多个字符串变量作为属性。我正在使用具有键和值参数的方法。我试图从xml文件提供键和值。为此,必须用Customer类的属性(字符串变量)代替值。

Customer
{
  public string Name{return _name};

  public string Address{return _address};
}


CallInput
{
  StringTempelate tempelate = new StringTempelate();
  foreach(item in items)
  tempelate .SetAttribure(item.key, item.Value -->   //Say this value is Name, so it has to substitute Customer.Name
}

可能吗?


阅读 256

收藏
2020-05-19

共1个答案

小编典典

您可以使用反射来设置“按名称”属性。

using System.Reflection;
...
myCustomer.GetType().GetProperty(item.Key).SetValue(myCustomer, item.Value, null);

您还可以使用GetValue读取属性,或使用GetType()。GetProperties()获取所有属性名称的列表,该列表返回PropertyInfo的数组(Name属性包含属性名称)

2020-05-19