2011-12-25 22 views
1

我有一個一流的呼叫人:我可以使用字符串str =「id」,然後person.str = 1嗎?

public class Person 
{ 
    public int id{get;set;} 
    public string name{get;set;} 
    //and many others 
} 

有沒有一種方法來設置值屬性不會像正規途徑:person.id=1 但使用這樣的string str="id"person.str=1

我想要這樣,因爲我有很多屬性,我收到屬性名稱和他的價值列表。所以我想,以避免長時間switch-case及用途:

foreach(var item in MyList.Keys) 
{ 
    person.item=MyList[item]; 
} 
+0

你有屬性詞典嗎? – dotnetstep 2011-12-25 12:32:21

回答

2
public class Person 
{ 
    public int Id{get;set;} 
    public string Name{get;set;} 
    //and many others 
} 




Dictionary<string,object> properties = new Dictionary<string,object>(); 
       properties.Add("Id",1); 
       properties.Add("Name", "TestName"); 

       Person p = new Person(); 
       foreach (KeyValuePair<string, object> obj in properties) 
       { 
        p.GetType().GetProperty(obj.Key).SetValue(p, obj.Value, null); 
       } 

這可能適用於您。確保你有適當的propertyname外殼。

+0

謝謝!!!我試了一下。 – Hadas 2011-12-25 12:39:48

+0

偉大的解決方案! 你能告訴如何以同樣的方式獲得價值嗎? – Hadas 2011-12-25 13:33:12

+0

獲得值p.GetType()。GetProperty(obj.Key,System.Reflection.BindingFlags.IgnoreCase).GetValue(p,null); ..但仔細它返回對象,你必須轉換回原始類型或一些通用機能的研究。 – dotnetstep 2011-12-25 15:01:39

0

您可以使用reflection這個或dynamic類型在.NET 4.0中。

+0

我讀過它,但不明白它是如何幫助我的。 ? – Hadas 2011-12-25 12:36:47

相關問題