我想MethodInfo
从具有仅在运行时知道的类型参数的泛型类中获取一种方法。
这是我如何MethodInfo
从非泛型类中获取泛型方法的方法:
class MyClass
{
public void MyMethod<T> (T arg)
{
}
}
static MethodInfo Resolve (Type type)
{
Expression<Action<MyClass, object>> lambda = (c, a) => c.MyMethod (a);
MethodCallExpression call = lambda.Body as MethodCallExpression;
return call
.Method // Get MethodInfo for MyClass.MyMethod<object>
.GetGenericMethodDefinition () // Get MethodInfo for MyClass.MyMethod<>
.MakeGenericMethod (type); // Get MethodInfo for MyClass.MyMethod<int>
}
Resolve (typeof (int)).Invoke (new MyClass (), new object[] {3});
现在,如果我想用泛型类尝试类似的东西:
class MyClass<T>
{
public void MyMethod (T arg)
{
}
}
static MethodInfo Resolve (Type type)
{
Expression<Action<MyClass<object>, object>> lambda = (c, a) => c.MyMethod (a);
MethodCallExpression call = lambda.Body as MethodCallExpression;
return call
.Method // Get MethodInfo for MyClass<object>.MyMethod
.SomeMagicMethod (); // FIXME: how can I get a MethodInfo
// for MyClass<T>.MyMethod where typeof (T) == type?
}
Resolve (typeof (string)).Invoke (new MyClass<string> (), new object[] {"Hello, World!"});
可能吗?