繁体   English   中英

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

[英]Using C# reflection to call a constructor

我有以下场景:

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)创建一个Addition类型的新对象Addition(int a)

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

这可能吗?

我不认为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 });
    }
}

编辑:是的, Activator.CreateInstance也可以。 如果你想要更多地控制事物,找出参数名称等,请使用GetConstructor 。如果你只是想调用构造函数, Activator.CreateInstance很棒。

是的,您可以使用Activator.CreateInstance

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM