2012-02-06 91 views
5

我有一個包含超過100個字段和值的字典集合。有沒有辦法使用這個集合填充一個有100個字段的巨大類?從字典中填充類

該字典中的關鍵字對應於我的類的屬性名稱,值將是該類的屬性的值。

Dictionary<string, object> myDictionary = new Dictionary<string, object>(); 
myDictionary.Add("MyProperty1", "Hello World"); 
myDictionary.Add("MyProperty2", DateTime.Now); 
myDictionary.Add("MyProperty3", true); 

填充以下類的屬性。

public class MyClass 
{ 
    public string MyProperty1 {get;set;} 
    public DateTime MyProperty2 {get;set;} 
    public bool MyProperty3 {get;set;} 
} 
+0

你意味着填充班級?或生成類?如果是前者,只需使用反射。 – ColinE 2012-02-06 20:55:48

+0

爲什麼你的類有數百個屬性,而不是可以描述每個數據段的接口或類型的集合類,是否有原因? – 2012-02-06 20:56:08

回答

8

您可以使用GetProperties得到的屬性列表對於給定的類型和使用SetValue爲給定的屬性設置一個特定值:

MyClass myObj = new MyClass(); 
... 
foreach (var pi in typeof(MyClass).GetProperties()) 
{ 
    object value; 
    if (myDictionary.TryGetValue(pi.Name, out value) 
    { 
      pi.SetValue(myObj, value); 
    } 
} 
1

使用

MyClass yourinstance... 

foreach (var KVP in myDictionary) 
{ 
    yourinstance.GetType().GetProperty (KVP.Key).GetSetMethod().Invoke (yourinstance, new object[] { KVP.Value }); 
}