[英]How to invoke a method with a generic return type using reflection
我正在尝试使用具有通用返回类型的反射调用方法,如下所示:
public class SomeClass<T>
{
public List<T> GetStuff();
}
我通过调用存储库的GetClass<T>
泛型方法获得SomeClass的实例。
MethodInfo lGetSomeClassMethodInfo = typeof(IRepository)
.GetMethod("GetClass")
.MakeGenericMethod(typeof(SomeClass<>);
object lSomeClassInstance = lGetSomeClassMethodInfo.Invoke(
lRepositoryInstance, null);
之后,这是我尝试调用GetStuff方法的地方:
typeof(SomeClass<>).GetMethod("GetStuff").Invoke(lSomeClassInstance, null)
我对方法具有通用参数的事实感到惊讶。 但是,我不能使用MakeGenericMethod来解析返回类型。 另外,如果我使用lSomeClassInstance.GetType()
代替typeof(SomeClass<>)
(应该具有已解析的类型),则GetMethod("GetStuff")
返回null!
UPDATE
我已经找到了解决方案,并将在不久后发布答案。
无论出于何种原因,即使解析了类型之后, GetClass
返回的SomeClass实例也不允许您调用GetStuff
方法。
最重要的是,您应该首先简单地构造SomeClass,然后调用该方法。 像这样:
typeof(SomeClass<>)
.MakeGenericType(StuffType)
.GetMethod("GetStuff")
.Invoke(lSomeClassInstance, null);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.