使用通用类中定义的泛型参数调用非泛型方法

问题描述:

这是我的问题;使用通用类中定义的泛型参数调用非泛型方法

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的方法上调用。

我应该如何调用该方法?

您对错误的对象调用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