使用 C # 反射调用构造函数

我有以下情况:

class Addition{
public Addition(int a){ a=5; }
public static int add(int a,int b) {return a+b; }
}

我打电话给下列人士,要求他们加入另一个班级:

string s="add";
typeof(Addition).GetMethod(s).Invoke(null, new object[] {10,12}) //this returns 22

我需要一种类似于上面的反射语句的方法来使用 Addition(int a)创建一个类型为 Add 的新对象

所以我有字符串 s= "Addition",我想创建一个新的对象使用反射。

这可能吗?

114339 次浏览

I don't think GetMethod will do it, no - but GetConstructor will.

using System;
using System.Reflection;


class Addition
{
public Addition(int a)
{
Console.WriteLine("Constructor called, a={0}", a);
}
}


class Test
{
static void Main()
{
Type type = typeof(Addition);
ConstructorInfo ctor = type.GetConstructor(new[] { typeof(int) });
object instance = ctor.Invoke(new object[] { 10 });
}
}

EDIT: Yes, Activator.CreateInstance will work too. Use GetConstructor if you want to have more control over things, find out the parameter names etc. Activator.CreateInstance is great if you just want to call the constructor though.