使用Reflection调用包含通用参数的静态方法

时间:2010-06-16 10:18:39

标签: c# generics reflection

执行以下代码时,我收到此错误“无法对ContainsGenericParameters为true的类型或方法执行后期绑定操作。”

class Program
{
    static void Main(string[] args)
    {
        MethodInfo MI = typeof(MyClass).GetMethod("TestProc");
        MI.MakeGenericMethod(new [] {typeof(string)});
        MI.Invoke(null, new [] {"Hello"});
    }
}

class MyClass
{
    public static void TestProc<T>(T prefix) 
    {
        Console.WriteLine("Hello");
    }
}

上面的代码只是我面临的实际问题的缩放版本。请帮忙。

2 个答案:

答案 0 :(得分:28)

您正在调用MethodInfo.MakeGenericMethod,但丢弃了返回值。 返回值本身就是您想要Invoke的方法:

MethodInfo genericMethod = MI.MakeGenericMethod(new[] { typeof(string) });
genericMethod.Invoke(null, new[] { "Hello" });

答案 1 :(得分:3)

您发布的代码唯一的问题是:

MI.MakeGenericMethod(new [] {typeof(string)}); 

应该是

MI = MI.MakeGenericMethod(new [] {typeof(string)}); 

你没有抓住对'烘焙'通用的引用。

相关问题