在 .NET 中使用反射调用泛型方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6204326/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Calling generic method using reflection in .NET
提问by yshchohaleu
I have a question. Is it possible to call generic method using reflection in .NET? I tried the following code
我有个问题。是否可以在 .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);
But it throws the following exception "Late bound operations cannot be performed on types or methods for which ContainsGenericParameters is true."
但它会引发以下异常“无法对 ContainsGenericParameters 为 true 的类型或方法执行后期绑定操作。”
回答by Jon Skeet
You're not using the result of MakeGenericMethod- which doesn't change the method you call it on; it returns another object representing the constructed method. You should have something like:
你没有使用 - 的结果,MakeGenericMethod它不会改变你调用它的方法;它返回另一个表示构造方法的对象。你应该有类似的东西:
method = method.MakeGenericMethod(typeof(SomeClass));
var result = method.Invoke(service, null);
(or use a different variable, of course).
(当然,或者使用不同的变量)。
回答by jason
You need to say
你需要说
method = method.MakeGenericMethod(typeof(SomeClass));
at a minumum and preferably
最低限度,最好是
var constructedMethod = method.MakeGenericMethod(typeof(SomeClass));
constructedMethod.Invoke(service, null);
as instances of MethodInfoare immutable.
因为实例MethodInfo是不可变的。
This is the same concept as
这是相同的概念
string s = "Foo ";
s.Trim();
Console.WriteLine(s.Length);
string t = s.Trim();
Console.WriteLine(t.Length);
causing
造成
4
3
to print on the console.
在控制台上打印。
By the way, your error message
顺便说一下,你的错误信息
"Late bound operations cannot be performed on types or methods for which
ContainsGenericParametersistrue."
“不能对
ContainsGenericParametersis 的类型或方法执行后期绑定操作true。”
if your clue that methodstill contains generic parameters.
如果您的线索method仍然包含通用参数。

