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

sca*_*man 90 c# reflection constructor

我有以下场景:

class Addition{
 public Addition(int a){ a=5; }
 public static int add(int a,int b) {return a+b; }
}
Run Code Online (Sandbox Code Playgroud)

我通过以下方式调用另一个类:

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

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

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

这可能吗?

Jon*_*eet 158

我不认为GetMethod会这样做,不 - 但GetConstructor愿意.

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 });
    }
}
Run Code Online (Sandbox Code Playgroud)

编辑:是的,Activator.CreateInstance也会工作.使用GetConstructor,如果你想拥有的东西上更多的控制,找出参数名称等Activator.CreateInstance是伟大的,如果你只是想虽然调用构造函数.

  • 因此,如果要缓存委托(在多次调用相同的构造函数时的性能增强),首选`GetConstructor`,但对于一次性使用`Activator`会更容易. (4认同)
  • @AkshayJoy:"它的工作"还不够信息.我告诉过你如何机械地转换它 - 另一个选择是确保你理解C#代码,然后确保你知道用于构造数组的VB语法.不希望成为卑鄙,如果这是一个太大的挑战,那么你应该真的*真的*远离反思. (3认同)

Ben*_*igt 46

是的,你可以使用 Activator.CreateInstance

  • 这确实需要一个正确的答案 (2认同)