【问题标题】:Reflection to invoke the constructor with ConstructorInfo使用 ConstructorInfo 调用构造函数的反射
【发布时间】:2012-11-23 05:37:09
【问题描述】:

在下面这样一个非常简单的类中,

class Program 
{

    public Program(int a, int b, int c)
    {
        Console.WriteLine(a);
        Console.WriteLine(b);
        Console.WriteLine(c);
    }
 }

我使用反射来调用构造函数

这样的……

   var constructorInfo = typeof(Program).GetConstructor(new[] { typeof(int), typeof(int),      typeof(int) });
        object[] lobject = new object[] { };
        int one = 1;
        int two = 2;
        int three = 3;
        lobject[0] = one;
        lobject[1] = two;
        lobject[2] = three;

        if (constructorInfo != null)
        {
            constructorInfo.Invoke(constructorInfo, lobject.ToArray);
        }

但我收到一条错误消息,提示“对象与目标类型构造函数信息不匹配”。

非常感谢任何帮助/cmets。 提前致谢。

【问题讨论】:

    标签: c# .net visual-studio-2010 reflection .net-4.0


    【解决方案1】:

    您无需将constructorInfo 作为参数传递,只要您调用构造函数,而不是对象的实例方法。

    var constructorInfo = typeof(Program).GetConstructor(
                              new[] { typeof(int), typeof(int), typeof(int) });
    if (constructorInfo != null)
    {
        object[] lobject = new object[] { 1, 2, 3 };
        constructorInfo.Invoke(lobject);
    }
    

    对于KeyValuePair<T,U>:

    public Program(KeyValuePair<int, string> p)
    {
        Console.WriteLine(string.Format("{0}:\t{1}", p.Key, p.Value));
    }
    
    static void Main(string[] args)
    {
        var constructorInfo = typeof(Program).GetConstructor(
                                 new[] { typeof(KeyValuePair<int, string>) });
        if (constructorInfo != null)
        {
            constructorInfo.Invoke(
                new object[] { 
                    new KeyValuePair<int, string>(1, "value for key 1") });
        }
    
        Console.ReadLine();
    }
    

    【讨论】:

    • 假设如果我在构造函数中有一个键值对,那么我可以用同样的方法调用吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-01-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多