2009-08-18 156 views
15

我有类(客户),它拥有超过200个字符串变量属性。我正在使用key和value参数的方法。我试图从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 
} 

这可能吗?

+6

也许你应该考虑重新设计你的班级,200个属性有点疯狂:p 但是对于你来说,方法反思是一种方式。 您可以使用Dictionary 作为示例。 – 2009-08-18 12:40:19

+0

你找约翰

互联网络街头
2009-08-18 12:41:48

+0

@约翰·诺兰,只是类似于 – Mohanavel 2009-08-18 12:44:48

回答

20

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

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

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

13

那么,您可以使用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<Customer, string>委托实例 - 这将是更快,更复杂。有关更多信息,请参阅我的博客文章creating delegates via reflection

4

使用反射和字典对象作为您的项目集合。

Dictionary<string,string> customerProps = new Dictionary<string,string>(); 
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)); 
} 
5

反射是一个选项,但200个属性是...很多。碰巧,我目前正在研究类似的问题,但这些类是由code-gen创建的。为了适应“按名称”的用法,我(在代码生成阶段)添加一个索引:

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"); 
     } 
    } 
} 

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