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

查看:106
本文介绍了使用 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

我需要一种类似于上述反射语句的方法,使用 Addition(int a)

I need a way similar to the above reflection statement to create a new object of type Addition using Addition(int a)

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

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

这可能吗?

推荐答案

我认为 GetMethod 不会这样做,不会 - 但 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天全站免登陆