字符串到变量名称

我有类(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 } 

可能吗?

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

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

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

好吧,您可以使用Type.GetProperty(name)获取PropertyInfo ,然后调用GetValue

例如:

 // There may already be a field for this somewhere in the framework... private static readonly object[] EmptyArray = new object[0]; ... PropertyInfo prop = typeof(Customer).GetProperty(item.key); if (prop == null) { // Eek! Throw an exception or whatever... // You might also want to check the property type // and that it's readable } string value = (string) prop.GetValue(customer, EmptyArray); template.SetTemplateAttribute(item.key, value); 

请注意,如果您经常这样做,您可能希望将属性转换为Func委托实例 – 这将更快,但更复杂。 有关详细信息,请参阅我的博文,了解如何通过reflection创建代理

反思是一种选择,但200个属性……很多。 碰巧的是,我现在正在做类似这样的事情,但这些类是由代码生成的。 为了适应“按名称”使用,我添加了一个索引器(在代码生成阶段):

 public object this[string propertyName] { get { switch(propertyName) { /* these are dynamic based on the the feed */ case "Name": return Name; case "DateOfBirth": return DateOfBirth; ... etc ... /* fixed default */ default: throw new ArgumentException("propertyName"); } } } 

这给了“名字”的便利,但性能很好。

使用reflection和字典对象作为项集合。

 Dictionary customerProps = new Dictionary(); Customer myCustomer = new Customer(); //Or however you're getting a customer object foreach (PropertyInfo p in typeof(Customer).GetProperties()) { customerProps.Add(p.Name, p.GetValue(customer, null)); }