使用C#反射来调用构造函数 [英] Using C# reflection to call a constructor

查看:418
本文介绍了使用C#反射来调用构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下情形:

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

我打电话通过添加另一个类:

I am calling add in another class by:

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

我需要类似上面的反射语句中使用创建类型增加了一个新对象的方式加(int类型的)

所以我有字符串 s =加法,我想创建使用反射的新对象。

So I have string s= "Addition", I want to create a new object using reflection.

这可能吗?

推荐答案

我不认为 GetMethod 将做到这一点,没有 - 但<一个href=\"http://msdn.microsoft.com/en-us/library/system.type.getconstructor.aspx\"><$c$c>GetConstructor会的。

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 });
    }
}

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

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.

这篇关于使用C#反射来调用构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆