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

2023-09-03 00:02:44 作者:ご屌炸天的节奏ヾ

我有一个问题。是否有可能在.NET中使用反射来调用泛型方法? 我尝试以下code

I have a question. Is it possible to call generic method using reflection in .NET? I tried the following code

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);

但它抛出以下异常后期绑定操作不能在类型或方法,其中ContainsGenericParameters是真正的执行。

But it throws the following exception "Late bound operations cannot be performed on types or methods for which ContainsGenericParameters is true."

推荐答案

您使用的不是结果 MakeGenericMethod - 它不会改变你怎么称呼它的方法上;它返回重新$ P $另一个对象psenting的构造方法。你应该是这样的:

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:

method = method.MakeGenericMethod(typeof(SomeClass));
var result = method.Invoke(service, null);

(或使用过程中的不同变量)。

(or use a different variable, of course).