Tim*_*ter 2 c# factory constraints generic-collections
我正在尝试编写一个工厂方法,该方法将创建抽象泛型集合类的派生实例.这是基类......
abstract class ItemBase { }
abstract class CollectionBase<T> : Collection<T> where T : ItemBase, new() { }
Run Code Online (Sandbox Code Playgroud)
......及其派生类......
class Item : ItemBase { }
class ItemCollection : CollectionBase<Item> {}
Run Code Online (Sandbox Code Playgroud)
现在,我想要一个将创建ItemCollection的工厂方法.但请注意,派生类Item和ItemCollection对于包含此工厂方法的类是未知的.这就是我想象的应该......
static T CreateItemCollection<T>() where T : CollectionBase<ItemBase>, new()
{
return new T();
}
Run Code Online (Sandbox Code Playgroud)
......我想像这样调用它......
var collection = CreateItemCollection<ItemCollection>();
Run Code Online (Sandbox Code Playgroud)
但是工厂方法不会编译,因为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();
}
Run Code Online (Sandbox Code Playgroud)
只有集合类型需要无参数构造函数.你这称之为:
var collection = CreateItemCollection<ItemCollection, Item>();
Run Code Online (Sandbox Code Playgroud)