2014-12-05 98 views
3

我有一個類可以說5個屬性匹配字符與類屬性名稱

Int32 Property1; 
Int32 Property2; 
Int32 Property3; 
Int32 Property4; 
Int32 Property5; 

現在我要動態設置的只有3個其中三個屬性的值。到目前爲止是好的,但我的問題是我在運行時將這三個屬性名稱作爲字符串。 可以說,這樣的事情..

List<String> GetPropertiesListToBeSet() 
{ 
    List<String> returnList = new List<String>(); 
    returnList.Add("Property1"); 
    returnList.Add("Property3"); 
    returnList.Add("Property4"); 
    retun returnList; 
} 

所以現在,

List<String> valuesList = GetPropertiesToBeSet(); 

foreach (String valueToSet in valuesList) 
{ 
// How Do I match these Strings with the property Names to set values 
    Property1 = 1; 
    Property3 = 2; 
    Property4 = 3; 
} 
+0

爲什麼你不能使用'Dictionary '鍵是屬性名? – 2014-12-05 14:00:14

+0

或更好的數組或字典其中索引是「屬性號碼」(例如,'Property1'的'1'等) – 2014-12-05 14:23:55

回答

6

你可以做這樣的事情。屬性是你的類

 Properties p = new Properties(); 
     Type tClass = p.GetType(); 
     PropertyInfo[] pClass = tClass.GetProperties(); 

     int value = 0; // or whatever value you want to set 
     foreach (var property in pClass) 
     { 
      property.SetValue(p, value++, null); 
     } 
3

假設該類包含他們的名字是Properties。您可以使用GetProperty()方法獲取PropertyInfo然後SetValue()方法:

Properties p = new Properties(); 
Type t = p.GetType(); //or use typeof(Properties) 

int value = 1; 
foreach (String valueToSet in valuesList) { 
    var bindingFlags = BindingFlags.NonPublic | BindingFlags.Instance; //because they're private properties 
    t.GetProperty(valueToSet, bindingFlags).SetValue(p, value++); //where p is the instance of your object 
} 
相關問題