2009-08-18 157 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"); 
     } 
    } 
} 

這給「名字」的便利,但良好的性能。