6
這是我的問題;使用通用類中定義的泛型參數調用非泛型方法
public class MyClass<T>
{
public void DoSomething(T obj)
{
....
}
}
我所做的是:
var classType = typeof(MyClass<>);
Type[] classTypeArgs = { typeof(T) };
var genericClass = classType.MakeGenericType(classTypeArgs);
var classInstance = Activator.CreateInstance(genericClass);
var method = classType.GetMethod("DoSomething", new[]{typeof(T)});
method.Invoke(classInstance, new[]{"Hello"});
在上述情況下,我得到的例外是:晚綁定操作不能在類型或採用何種方法ContainsGenericParameters是真正的執行。
如果我嘗試使該方法爲通用,那麼它將再次失敗併產生異常: MakeGenericMethod只能在MethodBase.IsGenericMethodDefinition爲true的方法上調用。
我應該如何調用該方法?
完美!這讓我難倒了好幾個小時.... – CRG 2012-09-09 13:32:46