假设我有几个派生类,其基类是泛型类。每个派生类都使用特定的类型覆盖继承基类(但所有类型也都是从单个基类型派生的。)
例如:
我有一个基本行类
class RowBase
{
//some properties and abstract methods
}
我有两个特定的行类派生自行基类
class SpecificRow1 : RowBase
{
//some extra properties and overrides
}
class SpecificRow2 : RowBase
{
//some extra properties and overrides
}
然后我有一个第二个基类,它是一个泛型类,包含RowBase派生类的集合
class SomeBase<T> where T : RowBase
{
ICollection<T> Collection { get; set; }
//some other properties and abstract methods
}
然后我有两个派生自SomeBase的类但使用不同的特定行类
class SomeClass1 : SomeBase<SpecificRow1>
{
//some properties and overrides
}
class SomeClass2 : SomeBase<SpecificRow2>
{
//some properties and overrides
}
现在,在我的主要或更大的范围内,我想创建一个包含SomeClass1和SomeClass2对象的列表/集合。像
ICollection<???> CombinedCollection = new ...
CombinedCollection.Add(new SomeClass1())
CombinedCollection.Add(new SomeClass2())
.
.
.
//add more objects and do something about the collection
.
.
.
问题是:是否可以进行此类收集?如果有可能,我该如何实现?如果不是,可以采用哪种替代方式?
答案 0 :(得分:5)
这可以在Covariance and Contravariance的帮助下完成。
添加一个新界面并使T参数协变(使用 out 关键字):
interface ISomeRow<out T> where T : RowBase
{
}
SomeBase应该继承这样的接口:
class SomeBase<T> : ISomeRow<T> where T : RowBase
{
//some other properties and abstract methods
}
然后,以下内容将起作用:
List<ISomeRow<RowBase>> myList = new List<ISomeRow<RowBase>>();
myList.Add(new SomeClass1());
myList.Add(new SomeClass2());
希望这是你正在寻找的东西:)