[英]C# - how to create an inherited generic collection from a factory method
我正在尝试编写一个工厂方法,该方法将创建抽象泛型集合类的派生实例。 这是基类......
abstract class ItemBase { }
abstract class CollectionBase<T> : Collection<T> where T : ItemBase, new() { }
......及其派生类......
class Item : ItemBase { }
class ItemCollection : CollectionBase<Item> {}
现在,我想要一个将创建ItemCollection的工厂方法。 但请注意,派生类Item和ItemCollection对于包含此工厂方法的类是未知的。 这就是我想象的应该......
static T CreateItemCollection<T>() where T : CollectionBase<ItemBase>, new()
{
return new T();
}
......我想像这样调用它......
var collection = CreateItemCollection<ItemCollection>();
但是工厂方法不会编译,因为ItemBase必须具有无参数构造函数。 并且invokation调用拒绝相信ItemCollection
是从CollectionBase<ItemBase>
派生的。
有人可以指点我正确的方向吗? 谢谢。
由于泛型不变性, ItemCollection
不是从CollectionBase<ItemBase>
派生的。 毕竟,您可以将ItemBase
添加到CollectionBase<ItemBase>
- 但您不希望ItemCollection
!
您需要在两个类型参数中使方法通用:
static T CreateItemCollection<TCollection, TItem>()
where TCollection : CollectionBase<TItem>, new()
where TItem : ItemBase
{
return new TCollection();
}
只有集合类型需要无参数构造函数。 你这称之为:
var collection = CreateItemCollection<ItemCollection, Item>();
这里的问题是泛型约束,在C#3.0中,有关于方差的任何余地。 相反,匹配相当严格。 由于ItemCollection派生自CollectionBase<Item>
因此它不被认为是从CollectionBase<ItemBase>
派生的,即使这些类型看似兼容。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.