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

Abr*_*mJP 14 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");
    }
}
Run Code Online (Sandbox Code Playgroud)

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

Aak*_*shM 31

你正在打电话MethodInfo.MakeGenericMethod但丢掉了返回值.该返回值本身是您要的方法Invoke:

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