c#-4.0 - 具有通用基类的派生类的集合

标签 c#-4.0

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

例如:

我有一个基行类

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
.
.
.

问题是:有可能有这样的收藏吗?如果可能的话,我怎样才能实现这一目标?如果没有,有什么替代方法?

最佳答案

这可以在 Covariance and Contravariance 的帮助下完成.

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

interface ISomeRow<out T> where T : RowBase
{
}

SomeBase 应该像这样继承该接口(interface):

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());

希望这就是您正在寻找的:)

关于c#-4.0 - 具有通用基类的派生类的集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13280108/

相关文章:

c# - 如何将 DateTime 转换为 JulianDate?

c# - 在字符串中添加句点

c# - 只去掉字符串中最左边的字母,只去掉左边的字母

c# - .NET 4 中的自定义属性更改

c# - 使用静态字段时出现TypeInitializationError

c# - linq在何处和选择上的歧义

c# - 将不同类型的通用对象添加到通用列表中

wcf - 使用存储过程在数据库修改后更新上下文

c# - 基于矢量的生成器是创建条形码的最佳方式吗?

c# - 用于查询事件网络和关联连接的 WMI