开发者

How to invoke a method with a generic return type using reflection

I'm trying to invoke a method with reflection that has a generic return type, like this:

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

I get an instance of SomeClass with a call to a Repository's GetClass<T> generic method.

MethodInfo lGetSomeClassMethodInfo = typeof(IRepository)
    .GetMethod("GetClass")
    .MakeGenericMethod(typeof(SomeClass<>);
object lSomeClassInstance = lGetSomeClassMethodInfo.Invoke(
    lRepositoryInstance, null开发者_JS百科);

After that, this is where I try to invoke the GetStuff method:

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

I get an exception about the fact that the method has generic arguments. However, I can't use MakeGenericMethod to resolve the return type. Also, if instead of typeof(SomeClass<>) I use lSomeClassInstance.GetType() (which should have resolved types) GetMethod("GetStuff") returns null!

UPDATE

I have found the solution and will post the answer shortly.


For whatever reason, the instance of SomeClass returned by GetClass, even after the types have been resolved, doesn't allow you to call the GetStuff method.

The bottom line is that you should simply construct SomeClass first and then invoke the method. Like this:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜