我使用反射來找到一種通過這樣的字符串...使用反射創建通過的「類型」的內容表示的對象對象
Type currentType = Type.GetType(typeName);
話,我能得到一個列表特性該類型是這樣的...的
var props = currentType.GetProperties();
如何實例化這個類的一個新的對象,然後開始到該對象的總部設在道具列表屬性列表上的屬性分配值?
我使用反射來找到一種通過這樣的字符串...使用反射創建通過的「類型」的內容表示的對象對象
Type currentType = Type.GetType(typeName);
話,我能得到一個列表特性該類型是這樣的...的
var props = currentType.GetProperties();
如何實例化這個類的一個新的對象,然後開始到該對象的總部設在道具列表屬性列表上的屬性分配值?
使用你已經擁有的價值觀......
var created = Activator.CreateInstance(currentType);
foreach(var prop in props)
{
prop.SetValue(created, YOUR_PROPERTY_VALUE, null);
}
實例化currentType
有:
var newInst = Activator.CreateInstance(currentType);
,並指定屬性與價值:
propInfo.SetValue(newInst, propValue, BindingFlags.SetProperty, null, null, null);
哪裏propInfo
是從props
和propValue
的PropertyInfo
實例是要分配給屬性的對象。
編輯:
我總是朝着傾斜使用更詳細的SetValue
超載,因爲我曾與一個短在過去的問題,但propInfo.SetValue(newInst, propValue, null);
可以正常工作。
+1,打我給它。 – 2012-02-10 04:28:08