2009-09-30 72 views
1

我有一些基礎對象「汽車」,「狗」,「貓」他們實現了一個接口「IGWUIElement」。我有這些接口的列表:List myList。如何在實例化對象上使用反射調用方法?

在運行時我循環遍歷我的元素列表並通過檢查類的名稱(使用反射)我需要填充它們的屬性 - 這不是接口的一部分)。我有一個xml文檔描述propeties和我應該分配給他們的價值。這是我的接口實例。

IGWUIElement newUIElement = (IGWUIElement)Activator.CreateInstance(result); 

我該如何從特定值(請注意數據類型僅限於int和字符串)調用其名稱中的屬性。每個對象都有不同的屬性。

希望這是有道理...

/H4mm3r

回答

5

使用PropertyInfo.SetValue()

PropertyInfo piInstance = typeof(IGWUIElement).GetProperty("property_name"); 
piInstance.SetValue(newUIElement, value, null); 

更多msdn

4

你可以做到這一點,像這樣:

IGWUIElement element = myList[0]; 

// Set a string property 
element.GetType().InvokeMember("SomeStringProperty", BindingFlags.Instance | BindingFlags.Public | BindingFlags.SetProperty, Type.DefaultBinder, element, "The String Value"); 

// Set an int property 
element.GetType().InvokeMember("SomeIntProperty", BindingFlags.Instance | BindingFlags.Public | BindingFlags.SetProperty, Type.DefaultBinder, element, 3); 
相關問題