如何使用给定的 Type 对象调用泛型方法? [英] How to call generic method with a given Type object?
问题描述
我想用给定的类型对象调用我的泛型方法.
I want to call my generic method with a given type object.
void Foo(Type t)
{
MyGenericMethod<t>();
}
显然不起作用.
我怎样才能让它发挥作用?
How can I make it work?
推荐答案
您的代码示例将不起作用,因为泛型方法需要类型标识符,而不是 Type 类的实例.你必须使用反射来做到这一点:
Your code sample won't work, because the generic method expects a type identifier, not a an instance of the Type class. You'll have to use reflection to do it:
public class Example {
public void CallingTest()
{
MethodInfo method = typeof (Example).GetMethod("Test");
MethodInfo genericMethod = method.MakeGenericMethod(typeof (string));
genericMethod.Invoke(this, null);
}
public void Test<T>()
{
Console.WriteLine(typeof (T).Name);
}
}
请记住,这非常脆弱,我宁愿建议您寻找另一种模式来调用您的方法.
Do keep in mind that this is very brittle, I'd rather suggest finding another pattern to call your method.
另一种hacky解决方案(也许有人可以让它更简洁一些)是使用一些表达魔法:
Another hacky solution (maybe someone can make it a bit cleaner) would be to use some expression magic:
public class Example {
public void CallingTest()
{
MethodInfo method = GetMethod<Example>(x => x.Test<object>());
MethodInfo genericMethod = method.MakeGenericMethod(typeof (string));
genericMethod.Invoke(this, null);
}
public static MethodInfo GetMethod<T>(Expression<Action<T>> expr)
{
return ((MethodCallExpression) expr.Body)
.Method
.GetGenericMethodDefinition();
}
public void Test<T>()
{
Console.WriteLine(typeof (T).Name);
}
}
注意在 lambda 中将对象"类型标识符作为泛型类型参数传递.无法这么快地想出如何解决这个问题.无论哪种方式,我认为这是编译时安全的.不知何故感觉不对:/
Note passing the 'object' type identifier as a generic type argument in the lambda. Couldn't figure out so quickly how to get around that. Either way, this is compile-time safe I think. It just feels wrong somehow :/
这篇关于如何使用给定的 Type 对象调用泛型方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!