覆盖IEnumerable T.在哪里 [英] Override IEnumerable<T> Where

查看:59
本文介绍了覆盖IEnumerable T.在哪里的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了一个实现IEnumerable的类:

I've written a class that implements IEnumerable :

public class MyEnumerable : IEnumerable<MyClass>
{ 
    IEnumerator IEnumerable.GetEnumerator()
    {
        return this.GetEnumerator();
    }
    public IEnumerator<MyClass> GetEnumerator()
    {
        //Enumerate
    }
}

我想覆盖" Where方法.我想做的是:

I'd like to "override" the Where method. What I want to do is :

MyEnumerable myEnumerable = new MyEnumerable();
MyEnumerable myEnumerable2 = myEnumerable.Where(/*some predicate*/);

目前尚不可能,因为myEnumerable.Where()返回IEnumerable. 我想要的是myEnumerable.Where()返回一个MyEnumerable.

This is not possible for the moment because myEnumerable.Where() returns an IEnumerable. What I want is that myEnumerable.Where() returns a MyEnumerable.

可以这样做吗?

谢谢

推荐答案

可以-只需将Where方法添加到MyEnumerable. Linq Where方法是 extension 方法,因此从技术上讲,它不是替代方法.您正在隐藏" linq方法.

Sure - just add a Where method to MyEnumerable. The Linq Where method is an extension method, so it's not technically an override. you're "hiding" the linq method.

public class MyEnumerable : IEnumerable<MyClass>
{ 
    IEnumerator IEnumerable.GetEnumerator()
    {
        return this.GetEnumerator();
    }
    public IEnumerator<MyClass> GetEnumerator()
    {
        //Enumerate
    }

    public MyEnumerable Where()
    {
       // implement `Where`
    }
}

不过,有一些注意事项:

There are some caveats, though:

  • 仅在声明的类型为MyEnumerable的情况下才调用您的Where方法-不会在类型为IEnumerable<MyClass>的变量(或实现该方法的任何集合,如List<MyClass>
  • )上调用
  • 如果要与Linq保持一致,则还需要实现Where的多个重载.
  • Your Where method will only be called if the declared type is MyEnumerable - it will not be called on variables of type IEnumerable<MyClass> (or any collection that implements it, like List<MyClass>
  • There are several overloads of Where that will need to be implemented as well if you want to maintain consistently with Linq.

这篇关于覆盖IEnumerable T.在哪里的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆