2016-03-01 69 views
1

我有一個名爲AnchorLoadclass的類,其屬性爲diameter,thickness。我有一個列表中的屬性列表。現在我想遍歷一個列表並設置屬性的值爲:將字符串轉換爲屬性名稱

myanchor.(mylist[0]) = "200"; 

但它不工作。 我的代碼:

private void Form1_Load(object sender, EventArgs e) 
    { 
     AnchorLoadclass myanchor = new AnchorLoadclass(); 
     var mylist = typeof(AnchorLoadclass).GetProperties().ToList(); 
     myanchor.GetType().GetProperty(((mylist[0].Name).ToString())) = "200"; 

     myanchor.thickness ="0.0"; 
     propertyGrid1.SelectedObject = myanchor;   
    } 

回答

1

當你忘記在這個問題提了,行

myanchor.GetType().GetProperty(((mylist[0].Name).ToString())) = "200"; 

不編譯(請避免不工作)。你必須這樣做:

// 1. Get property itself: 
String name = "diameter"; // or mylist[0].Name or whatever name 

var propInfo = myanchor.GetType().GetProperty(name); 

// 2. Then assign the value 
propInfo.SetValue(myanchor, 200); 

通常情況下,這是一個很好的做法,

// Test, if property exists 
    if (propInfo != null) ... 

    // Test, if property can be written 
    if (propInfo.CanWrite) ... 

0

您應該使用的PropertyInfo對象上設置的屬性值(200)( myanchor)如下:

PropertyInfo propertyInfo = myanchor.GetType().GetProperty(((mylist[0].Name).ToString())); 
propertyInfo.SetValue(myanchor, 200); 
相關問題