我要与给定类型的对象叫我的一般方法。
I want to call my generic method with a given type object.
void Foo(Type t)
{
MyGenericMethod<t>();
}
显然是行不通的。
obviously doesn't work.
我怎样才能使它工作?
您code样品将无法正常工作,因为通用的方法需要一个类型标识符,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.
另外一个哈克解决方案(也许有人可以把它有点清洁剂)会使用一些EX pression魔法:
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);
}
}
请注意传递的对象类型标识符作为拉姆达一个泛型类型参数。无法弄清楚这么快怎么去解决这一问题。无论哪种方式,这是编译时的安全,我认为。它只是感觉错了不知何故:/
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 :/
上一篇:操作可能破坏运行?操作