C# 如何使用反射调用具有泛型返回类型的方法

C# 如何使用反射调用具有泛型返回类型的方法,c#,generics,reflection,C#,Generics,Reflection,我试图调用一个具有通用返回类型的反射方法,如下所示: public class SomeClass<T> { public List<T> GetStuff(); } 公共类SomeClass { 公共列表GetStuff(); } 通过调用存储库的GetClassgeneric方法,我得到了SomeClass的一个实例 MethodInfo lGetSomeClassMethodInfo = typeof(IRepository) .

我试图调用一个具有通用返回类型的反射方法,如下所示:

public class SomeClass<T>
{
    public List<T> GetStuff();
}    
公共类SomeClass
{
公共列表GetStuff();
}    
通过调用存储库的
GetClass
generic方法,我得到了SomeClass的一个实例

MethodInfo lGetSomeClassMethodInfo = typeof(IRepository)
    .GetMethod("GetClass")
    .MakeGenericMethod(typeof(SomeClass<>);
object lSomeClassInstance = lGetSomeClassMethodInfo.Invoke(
    lRepositoryInstance, null);
MethodInfo lGetSomeClassMethodInfo=typeof(IRepository)
.GetMethod(“GetClass”)
.MakeGenericMethod(typeof(SomeClass));
对象lSomeClassInstance=lGetSomeClassMethodInfo.Invoke(
lRepositoryInstance,null);
在此之后,我将尝试调用GetStuff方法:

typeof(SomeClass<>).GetMethod("GetStuff").Invoke(lSomeClassInstance, null)
typeof(SomeClass).GetMethod(“GetStuff”).Invoke(lSomeClassInstance,null)
我得到一个例外,即该方法具有泛型参数。但是,我不能使用MakeGenericMethod来解析返回类型。此外,如果使用
lSomeClassInstance.GetType()
(应该有解析的类型)
GetMethod(“GetStuff”)
而不是
typeof(SomeClass)
返回null

更新


我已经找到了解决方案,并将很快发布答案。

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

底线是,您只需先构造SomeClass,然后调用该方法即可。如下所示:

typeof(SomeClass<>)
    .MakeGenericType(StuffType)
    .GetMethod("GetStuff")
    .Invoke(lSomeClassInstance, null);
typeof(SomeClass)
.MakeGenericType(填充类型)
.GetMethod(“GetStuff”)
.Invoke(lSomeClassInstance,null);