使用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 prefix) { Console.WriteLine("Hello"); } }
上面的代码只是我面临的实际问题的缩放版本。 请帮忙。
您正在调用MethodInfo.MakeGenericMethod
但丢弃返回值。 返回值本身就是您要Invoke
的方法:
MethodInfo genericMethod = MI.MakeGenericMethod(new[] { typeof(string) }); genericMethod.Invoke(null, new[] { "Hello" });
您发布的代码的唯一问题是:
MI.MakeGenericMethod(new [] {typeof(string)});
应该
MI = MI.MakeGenericMethod(new [] {typeof(string)});
你没有抓住对’烘焙’generics的引用。