[英]Generic collection of generic types
我想知道什么是解决此问题的最佳方法:
object GetCollection(T1, T2)
{
return new T1<T2>;
}
好吧,我知道这将不会编译,但它表明了我的观点。 我需要根据传递给T1的通用类型创建一个收集类型,并且该类型应包含T2类型的elementy,
深渊的想法? 提前致谢
您可以通过反射来完成。 否则,我建议您根据可能的T1列表使用接口。 像这样:
class GenericContainerOne<T> { }
class GenericContainerTwo<T> { }
class Construct { }
static void Main(string[] args)
{
GenericContainerOne<Construct> returnObject = (GenericContainerOne<Construct>)GetGenericObject(typeof(GenericContainerOne<>), typeof(Construct));
}
static object GetGenericObject(Type container, Type construct)
{
Type genericType = container.MakeGenericType(construct);
return Activator.CreateInstance(genericType);
}
你的意思是这样吗?
object GetCollection<T1, T2>() where T1 : IEnumerable<T2>, new()
{
return new T1();
}
如果您在编译时不知道类型,则需要将通用类型与反射绑定。 Microsoft上的这篇文章可能满足您的需求。
最简单的是这样的:
object GetCollection<T1, T2>()
{
return Activator.CreateInstance(typeof(T1).MakeGenericType(typeof(T2)));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.