Override IEnumerable Where

后端 未结 2 1827
小鲜肉
小鲜肉 2021-01-24 03:24

I\'ve written a class that implements IEnumerable :

public class MyEnumerable : IEnumerable
{ 
    IEnumerator IEnumerable.GetEnumerator()
    {
         


        
2条回答
  •  天涯浪人
    2021-01-24 03:55

    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
    { 
        IEnumerator IEnumerable.GetEnumerator()
        {
            return this.GetEnumerator();
        }
        public IEnumerator GetEnumerator()
        {
            //Enumerate
        }
    
        public MyEnumerable Where()
        {
           // implement `Where`
        }
    }
    

    There are some caveats, though:

    • Your Where method will only be called if the declared type is MyEnumerable - it will not be called on variables of type IEnumerable (or any collection that implements it, like List
    • There are several overloads of Where that will need to be implemented as well if you want to maintain consistently with Linq.

提交回复
热议问题