2010-06-08 29 views
2

我试图调用与反射的方法是有一个通用的返回类型,像这样的调用方法与通用返回类型:如何使用反射

public class SomeClass<T> 
{ 
    public List<T> GetStuff(); 
}  

我得到SomeClass的实例有调用存储库的GetClass<T>通用方法。

MethodInfo lGetSomeClassMethodInfo = typeof(IRepository) 
    .GetMethod("GetClass") 
    .MakeGenericMethod(typeof(SomeClass<>); 
object lSomeClassInstance = lGetSomeClassMethodInfo.Invoke(
    lRepositoryInstance, null); 

之后,这是我尝试调用GetStuff方法:

typeof(SomeClass<>).GetMethod("GetStuff").Invoke(lSomeClassInstance, null) 

我得到的事实,该方法具有通用参数异常。但是,我无法使用MakeGenericMethod来解析返回类型。另外,如果不是typeof(SomeClass<>)我使用lSomeClassInstance.GetType()(应该已经解决类​​型)GetMethod("GetStuff")返回null!

UPDATE

我已经找到了解决办法,不久将发布的答案。

回答

1

无论出于何种原因,即使在类型解析之后,由GetClass返回的SomeClass实例也不允许您调用GetStuff方法。

底线是,你应该简单地构造SomeClass,然后调用该方法。像这样:

typeof(SomeClass<>) 
    .MakeGenericType(StuffType) 
    .GetMethod("GetStuff") 
    .Invoke(lSomeClassInstance, null);