我想從一個只有在運行時才知道類型參數的泛型類中獲得方法的MethodInfo
。如何查找使用強類型反射的泛型類方法的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!"});
可能嗎?
因爲'C .Meth'和'C .Meth'是風馬牛不相及方法根據.NET類型系統,因爲他們的'DeclaringType'這是棘手s是不同的。 –
usr
2013-04-11 21:44:11
你能解決你的解決方案代碼嗎?您正在使用'method'變量作爲'MethodInfo'和'MethodInfo []'。甚至搜索數組匹配相同的變量。這是沒有意義的。 – kjbartel 2015-09-03 04:36:08
變量'method'確實應該是一個數組,但第二個搜索遍歷包含解決方案,所以它只是一個錯誤。考慮再次閱讀問題。 – r3c 2015-09-04 07:04:23