如何使用反射来调用一个泛型方法? [英] How do I use reflection to call a generic method?
问题描述
什么是调用一个泛型方法时,类型参数是不是在编译时已知的最佳方式,而是在运行时动态获得?
考虑下面的示例code - 在例()
方法中,什么是调用 GenericMethod&LT最简洁的方式; T>( )
使用键入
存储在的myType
变量?
公共类样品
{
公共void示例(字符串的typeName)
{
键入=的myType FindType(typeName的); //善有善报这里叫GenericMethod< T>()?
GenericMethod<&的myType GT;(); //这不起作用 //什么样的变化来调用静态方法< T>()?
Sample.StaticMethod<&的myType GT;(); //这也不起作用
} 公共无效GenericMethod< T>()
{
// ...
} 公共静态无效STATICMETHOD< T>()
{
// ...
}
}
您需要使用反射来获取开始与方法,然后用提供的参数类型构造它<一个href=\"http://msdn.microsoft.com/en-us/library/system.reflection.methodinfo.makegenericmethod.aspx\">MakeGenericMethod:
MethodInfo的方法= typeof运算(样本).GetMethod(GenericMethod);
MethodInfo的通用= method.MakeGenericMethod(的myType);
generic.Invoke(这一点,空);
对于静态方法,通过空
作为第一个参数调用
。这是无关的泛型方法 - 它只是普通的反射
如前所述,很多,这是因为使用动态
C#4简单 - 如果你可以使用类型推断,当然。它不会在类型推断不可用,比如在这个问题的确切例子案件有所帮助。
What's the best way to call a generic method when the type parameter isn't known at compile time, but instead is obtained dynamically at runtime?
Consider the following sample code - inside the Example()
method, what's the most concise way to invoke GenericMethod<T>()
using the Type
stored in the myType
variable?
public class Sample
{
public void Example(string typeName)
{
Type myType = FindType(typeName);
// What goes here to call GenericMethod<T>()?
GenericMethod<myType>(); // This doesn't work
// What changes to call StaticMethod<T>()?
Sample.StaticMethod<myType>(); // This also doesn't work
}
public void GenericMethod<T>()
{
// ...
}
public static void StaticMethod<T>()
{
//...
}
}
You need to use reflection to get the method to start with, then "construct" it by supplying type arguments with MakeGenericMethod:
MethodInfo method = typeof(Sample).GetMethod("GenericMethod");
MethodInfo generic = method.MakeGenericMethod(myType);
generic.Invoke(this, null);
For a static method, pass null
as the first argument to Invoke
. That's nothing to do with generic methods - it's just normal reflection.
As noted, a lot of this is simpler as of C# 4 using dynamic
- if you can use type inference, of course. It doesn't help in cases where type inference isn't available, such as the exact example in the question.
这篇关于如何使用反射来调用一个泛型方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!