在调用.NET使用反射泛型方法 [英] Calling generic method using reflection in .NET

查看:483
本文介绍了在调用.NET使用反射泛型方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个问题。是否有可能在.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).

这篇关于在调用.NET使用反射泛型方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆