函数返回一个泛型类型,其值仅在运行时已知

Ste*_*rdi 5 c# generics reflection

我需要使用如下通用接口:

public interface IContainer<T>
{
    IEnumerable<IContent<T>> Contents { get; }
}
Run Code Online (Sandbox Code Playgroud)

实现此接口的对象由以下通用方法返回:

IContainer<T> GetContainer<T>(IProperty property);
Run Code Online (Sandbox Code Playgroud)

T在运行时之前,类型是未知的.

使用反射我可以调用GetContainer<T>方法并获得结果.

我的问题是我不知道如何枚举具有类型的结果Object(因此我无法将其强制转换IEnumerable).

我也试过如下铸造,但它不起作用(它说"预期类型"):

var myContainer = genericMethodInfo.Invoke(
                           myService, 
                           new object[] { property })
    as typeof(IContainer<>).MakeGenericType(type);
Run Code Online (Sandbox Code Playgroud)

type运行时类型在哪里,myService是暴露GetContainer<T>方法的服务,并且propertyIProperty根据需要的类型.

更新:在我的博客中查看我的完整解决方案:http://stefanoricciardi.com/2010/02/18/generics-with-type-uknown-at-compile-time/

归档时间:

查看次数:

3269 次

最近记录:

15 年,10 月 前