簡體   English   中英

使用反射創建由“類型”對象的內容表示的對象

[英]Using reflection to create an object represented by the contents of a “Type” object

我正在使用反射通過這樣的字符串找到類型...

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);

propInfoPropertyInfo從實例propspropValue是要分配給屬性的對象。

編輯:

我總是傾向於使用更冗長的SetValue重載,因為過去我遇到過簡短的問題,但是propInfo.SetValue(newInst, propValue, null); 可能也可以。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM