【问题标题】:Overriding generic IEnumerable interface in child class覆盖子类中的通用 IEnumerable 接口
【发布时间】:2011-03-20 23:14:54
【问题描述】:

我正在开发一个 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' 的查询模式的实现。'Where' 未找到。考虑明确指定范围变量 'childCollection' 的类型。”

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

仍然可以不为基集合类实现 IEnumerator 接口,而为所有子集合类实现。但这似乎是一种非 OODesign 方法。

我必须改变我的设计,还是有什么方法可以完全覆盖 IEnumerable 方法或效果?

【问题讨论】:

    标签: c# linq generics inheritance interface


    【解决方案1】:

    这样调整你的班级:

    public class CollectionBase<T> : IEnumerable<T>
      where T: EntityBase
    {
        protected EntityBase[] itemArray;
    
        //implementing the IEnumerable<EntityBase> is here. GetEnumerator method returns IEnumerator<EntityBase>
    
    }
    

    这样,基类就会知道底层类型。

    HTH。

    【讨论】:

    • 谢谢。我尝试了一些类似的方法。我有一些错误,我不够固执。现在效果很好。
    猜你喜欢
    • 1970-01-01
    • 2016-12-09
    • 1970-01-01
    • 2014-06-19
    • 1970-01-01
    • 2017-10-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多