覆盖子类中的通用IEnumerable接口

时间:2011-03-20 23:14:55

标签: c# linq generics inheritance interface

我正在开发一个ORM。我希望我的集合对象能够在Linq中使用。为了清楚起见,我在这里写的类是简化的。包含实体对象的数组位于CollectionBase类中。

class EntityBase
{
    public int fieldBase;
}

class EntityChild : EntityBase
{
    public int fieldChild;
}

class CollectionBase : IEnumerable<EntityBase>
{
    protected EntityBase[] itemArray;

    //implementing the IEnumerable<EntityBase> is here. GetEnumerator method returns IEnumerator<EntityBase>

}

class CollectionChild : CollectionBase, IEnumerable<EntityChild>
{
    public CollectionChild()
    {
        itemArray = new EntityChild[5]; //this is just an example.
    }
    //implementing the IEnumerable<EntityChild> is here. GetEnumerator method returns IEnumerator<EntityChild
}

我尝试了几件事。

如果CollectionChild没有扩展IEnumerable,则在此代码中无法访问EntityChild自己的字段:

var list = from c in childCollection
where c.fieldChild == 1; // c references to an EntityBase object.
select c;

如果CollectionChild扩展IEnumerable,甚至不可能在Linq中使用CollectionChild。

发生错误:“无法找到源类型'Generic_IEnumerableSample.CollectionChild'的查询模式的实现。'未找到的地方。考虑明确指定范围变量'childCollection'的类型。”

我试图找到一些方法来继承CollectionChild中的类(在实现IEnumerator的CollectionBase中)作为IEnumerator类。它不起作用,因为无法覆盖返回不同枚举器的方法。

仍然可以不为基本集合类实现IEnumerator接口,并为所有子集合类实现。但它似乎是一个非OODesign appraoch。

我必须更改我的设计,还是有办法完全覆盖IEnumerable方法或效果?

1 个答案:

答案 0 :(得分:2)

以这种方式调整你的课程:

public class CollectionBase<T> : IEnumerable<T>
  where T: EntityBase
{
    protected EntityBase[] itemArray;

    //implementing the IEnumerable<EntityBase> is here. GetEnumerator method returns IEnumerator<EntityBase>

}

这样,基类就会知道基础类型。

HTH。

相关问题