具有泛型基类的派生类的集合 [英] Collection of derived classes that have generic base class
问题描述
假设我有几个派生类,它们的基类是泛型类.每个派生类继承具有特定类型覆盖的基类(但所有类型也派生自单个基类型).
Say I have several derived classes whose base class is a generic class. Each derived class inherit the base class with a specific type override(but all types are also derived from a single base type).
例如:
我有一个基行类
class RowBase
{
//some properties and abstract methods
}
我有两个从行基类派生的特定行类
And I have two specific row classes that are derived from the row base class
class SpecificRow1 : RowBase
{
//some extra properties and overrides
}
class SpecificRow2 : RowBase
{
//some extra properties and overrides
}
然后我有第二个基类,它是一个泛型类,它包含一组来自 RowBase 的派生类
Then I have a second base class that is a generic class which contains a collection of derived classes from RowBase
class SomeBase<T> where T : RowBase
{
ICollection<T> Collection { get; set; }
//some other properties and abstract methods
}
然后我有两个类派生自 SomeBase 但使用不同的特定行类
Then I have two classes that derive from SomeBase but are using different specific row class
class SomeClass1 : SomeBase<SpecificRow1>
{
//some properties and overrides
}
class SomeClass2 : SomeBase<SpecificRow2>
{
//some properties and overrides
}
现在,在我的主要范围或更大的范围内,我想创建一个包含 SomeClass1 和 SomeClass2 对象的列表/集合.喜欢
Now that in my main or a bigger scope, I want to create a list/collection that consist both SomeClass1 and SomeClass2 objects. Like
ICollection<???> CombinedCollection = new ...
CombinedCollection.Add(new SomeClass1())
CombinedCollection.Add(new SomeClass2())
.
.
.
//add more objects and do something about the collection
.
.
.
问题是:有没有可能有这样的收藏?如果可能,我该如何实现?如果不是,还有什么替代方法?
The question is: is it possible to have such collection? If it is possible, how can I achieve this? If no, what can be an alternative way?
推荐答案
这可以在 协方差和逆变.
添加一个新接口,使 T 参数协变(使用 out 关键字):
Add a new interface that and make the T parameter covariant (using the out keyword):
interface ISomeRow<out T> where T : RowBase
{
}
SomeBase 应该像这样继承该接口:
SomeBase should inherit that interface like this:
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());
希望这就是你要找的 :)
Hope this is what you're looking for :)
这篇关于具有泛型基类的派生类的集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!