c# - 调用类型的空默认构造函数

标签 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**));
     }
}

但是我不知道在 GetConstructor 和 constructor.Invoke 方法中输入什么。我查看了 MSDN 文档,但我很不确定他们接受什么。我只想调用空的默认构造函数。

最佳答案

您可以使用:

var constructor = type.GetConstructor(Type.EmptyTypes);
p.SetValue(this, constructor.Invoke());

或者:

p.SetValue(this, Activator.CreateInstance(type));

请注意,我已将第一个参数替换为 this,因为 SetValue 方法需要您的 object 实例,而不是 PropertyInfo

关于c# - 调用类型的空默认构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28053895/

相关文章:

c# - 在 C# 中根据鼠标点击获取事件窗口名称

c# - 确定一个方法是否调用另一个包含新语句的程序集中的方法,反之亦然

c# - 获取类型的继承树

python - 在python中用父类方法覆盖__init__

c# - 当属性或变量改变值时触发事件

c# - Azure 服务总线队列在 NodeJs 中向 .NET 客户端发送消息

java - 检查原始字段的类型

c# - 使用反射打印自己的方法名、类库(可移植)

java - 我是构造函数新手,我如何为字符串传递 int ?

派生类型的构造函数