2012-01-01 110 views
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的方法上調用。

我應該如何調用該方法?

回答

11

您對錯誤的對象調用GetMethod。用綁定泛型類型來調用它,它應該可以工作。這是一個完整的示例,它可以正常工作:

using System; 
using System.Reflection; 

internal sealed class Program 
{ 
    private static void Main(string[] args) 
    { 
     Type unboundGenericType = typeof(MyClass<>); 
     Type boundGenericType = unboundGenericType.MakeGenericType(typeof(string)); 
     MethodInfo doSomethingMethod = boundGenericType.GetMethod("DoSomething"); 
     object instance = Activator.CreateInstance(boundGenericType); 
     doSomethingMethod.Invoke(instance, new object[] { "Hello" }); 
    } 

    private sealed class MyClass<T> 
    { 
     public void DoSomething(T obj) 
     { 
      Console.WriteLine(obj); 
     } 
    } 
} 
+0

完美!這讓我難倒了好幾個小時.... – CRG 2012-09-09 13:32:46