Jen*_*112 2 c# reflection constructor
我正在尝试在我的对象上实例化每个属性(类型为JobVmInput).到目前为止这是我的代码:
var properties = this.GetType().GetProperties();
foreach (var p in properties)
{
var type = p.PropertyType;
if (type.IsSubclassOf(typeof(JobVmInput)))
{
var constructor = type.cons.GetConstructor(**what to input here**);
p.SetValue(p, constructor.Invoke(**what to input here**));
}
}
Run Code Online (Sandbox Code Playgroud)
但是我不知道在GetConstructor和constructor.Invoke方法中输入什么.我查看了MSDN文档,但我对他们接受的内容非常不确定.我只想调用空的默认构造函数.
您可以使用:
var constructor = type.GetConstructor(Type.EmptyTypes);
p.SetValue(this, constructor.Invoke());
Run Code Online (Sandbox Code Playgroud)
要么:
p.SetValue(this, Activator.CreateInstance(type));
Run Code Online (Sandbox Code Playgroud)
请注意,我已经替换了第一个参数,this因为该SetValue方法需要一个object不是你的实例PropertyInfo
| 归档时间: |
|
| 查看次数: |
279 次 |
| 最近记录: |