我想学习如何在反射的帮助下创建一个类的对象,它有一个显式的构造函数。假设有一个班级学生:
class Student
{
private int _temp = 10;
private string name = "Vasya";
}
在这种情况下,创建实例时使用反射如下所示:
class Program
{
static void Main(string[] args)
{
Type type = typeof(Student);
ConstructorInfo info = type.GetConstructor(new Type[] { });
object student = info.Invoke(new object[] { });
}
}
但是,如果我的学生中出现了显式构造函数,例如:
class Student
{
private int temp;
private string name;
public Student(int temp, string name)
{
this.temp = temp;
this.name = name;
}
}
那么我应该如何在程序的调用部分传递参数呢?即这里:
ConstructorInfo info = type.GetConstructor(new Type[] { });
object student = info.Invoke(new object[] { });
你需要得到一个这样的构造函数:
并将参数传递给它:
为什么不只是