具有通用基类的派生类的集合

nod*_*ddy 5 c#-4.0

假设我有几个派生类,其基类是泛型类.每个派生类都使用特定的类型覆盖继承基类(但所有类型也都是从单个基类型派生的).

例如:

我有一个基本行类

class RowBase
{
    //some properties and abstract methods
}
Run Code Online (Sandbox Code Playgroud)

我有两个从行基类派生的特定行类

class SpecificRow1 : RowBase
{
    //some extra properties and overrides
}

class SpecificRow2 : RowBase
{
    //some extra properties and overrides
}
Run Code Online (Sandbox Code Playgroud)

然后我有一个第二个基类,它是一个泛型类,包含RowBase派生类的集合

class SomeBase<T> where T : RowBase
{
    ICollection<T> Collection { get; set; }
    //some other properties and abstract methods
}
Run Code Online (Sandbox Code Playgroud)

然后我有两个派生自SomeBase但使用不同特定行类的类

class SomeClass1 : SomeBase<SpecificRow1>
{
     //some properties and overrides
}

class SomeClass2 : SomeBase<SpecificRow2>
{
     //some properties and overrides
}
Run Code Online (Sandbox Code Playgroud)

现在,在我的主要或更大的范围内,我想创建一个包含SomeClass1和SomeClass2对象的列表/集合.喜欢

ICollection<???> CombinedCollection = new ...
CombinedCollection.Add(new SomeClass1())
CombinedCollection.Add(new SomeClass2())
.
.
.
//add more objects and do something about the collection
.
.
.
Run Code Online (Sandbox Code Playgroud)

问题是:是否可以进行此类收集?如果有可能,我该如何实现?如果不是,还有什么可以替代?

Bla*_*hma 5

这可以在协方差和逆变法的帮助下完成.

添加一个新接口并使T参数协变(使用out关键字):

interface ISomeRow<out T> where T : RowBase
{
}
Run Code Online (Sandbox Code Playgroud)

SomeBase应该继承这样的接口:

class SomeBase<T> : ISomeRow<T> where T : RowBase
{
    //some other properties and abstract methods
}
Run Code Online (Sandbox Code Playgroud)

然后,以下将工作:

List<ISomeRow<RowBase>> myList = new List<ISomeRow<RowBase>>();
myList.Add(new SomeClass1());
myList.Add(new SomeClass2());
Run Code Online (Sandbox Code Playgroud)

希望这是你要找的:)