在.NET中使用反射调用泛型方法

ysh*_*leu 40 .net generics reflection

我有个问题.是否可以在.NET中使用反射调用泛型方法?我尝试了以下代码

var service = new ServiceClass();
Type serviceType = service.GetType();
MethodInfo method = serviceType.GetMethod("Method1", new Type[]{});
method.MakeGenericMethod(typeof(SomeClass));
var result = method.Invoke(service, null);
Run Code Online (Sandbox Code Playgroud)

但它抛出以下异常"无法对ContainsGenericParameters为true的类型或方法执行后期绑定操作."

Jon*_*eet 104

您没有使用结果MakeGenericMethod- 这不会改变您调用它的方法; 它返回另一个表示构造方法的对象.你应该有类似的东西:

method = method.MakeGenericMethod(typeof(SomeClass));
var result = method.Invoke(service, null);
Run Code Online (Sandbox Code Playgroud)

(当然,或者使用不同的变量).

  • 首先google点击:)我爱你! (2认同)
  • @kuldeep:您应该对代码进行基准测试以找出影响。如果我在不了解有关您的系统的更多信息的情况下就做出影响预测,那将是愚蠢的。 (2认同)

jas*_*son 6

你需要说

method = method.MakeGenericMethod(typeof(SomeClass));
Run Code Online (Sandbox Code Playgroud)

在最低限度,最好是

var constructedMethod = method.MakeGenericMethod(typeof(SomeClass));
constructedMethod.Invoke(service, null);
Run Code Online (Sandbox Code Playgroud)

作为MethodInfo不可变的实例.

这与概念相同

string s = "Foo ";
s.Trim();
Console.WriteLine(s.Length);
string t = s.Trim();
Console.WriteLine(t.Length);
Run Code Online (Sandbox Code Playgroud)

造成

4
3
Run Code Online (Sandbox Code Playgroud)

在控制台上打印.

顺便说一下,你的错误信息

"后期绑定操作不能在类型或方法,其用于执行ContainsGenericParameterstrue".

如果你的线索method仍然包含通用参数.