Troubles implementing IEnumerable

后端 未结 7 866
清酒与你
清酒与你 2020-11-29 11:08

I\'m trying to write my own (simple) implementation of List. This is what I did so far:

using System;
using System.Collections.Generic;
using System.Linq;
us         


        
相关标签:
7条回答
  • 2020-11-29 11:24

    Read the error message more carefully; it is telling you exactly what you must do. You did not implement System.Collections.IEnumerable.GetEnumerator.

    When you implement the generic IEnumerable<T> you have to also implement System.Collections.IEnumerable's GetEnumerator.

    The standard way to do so is:

    public IEnumerator<T> GetEnumerator () { whatever }
    System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
    {
        return this.GetEnumerator();
    }
    
    0 讨论(0)
  • 2020-11-29 11:26

    Add the following method:

    IEnumerator IEnumerable.GetEnumerator()
    {
        return this.GetEnumerator();
    }
    
    0 讨论(0)
  • 2020-11-29 11:31

    There are two overloads of GetEnumerator() that you must implement. One comes from IEnumerable<T> and returns IEnumerator<T>. The other comes from IEnumerable and returns IEnumerator. The override should look like this:

    IEnumerator IEnumerable.GetEnumerator()

    This is because IEnumerable<T> implements IEnumerable.

    0 讨论(0)
  • 2020-11-29 11:33

    Since your class, MyList<T> inherits IEnumerable<out T> which in turn inherits the non-generic IEnumerable, you have two methods you need to implement:

    IEnumerator<T> IEnumerable<T>.GetEnumerator()
            {
                throw new NotImplementedException();
            }
    
            System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
            {
                throw new NotImplementedException();
            }
    

    An easy way to do this is when you declare your class:

    class MyList<T> : IEnumerable<T>
    

    Right click the IEnumerable<T> text and select Implement Interface > Implement Interface Explictly from the context menu.

    0 讨论(0)
  • You'll need to implement the non-generic GetEnumerator method as well:

    IEnumerator IEnumerable.GetEnumerator()
    {
        return GetEnumerator();
    }
    

    Since the IEnumerable<T> interface extends IEnumerable, you have to implement the methods declared on both.

    0 讨论(0)
  • 2020-11-29 11:38

    I got similar problem,though I implemented also IEnumerable and IEnumerable. I was using custom type (Person class) than generic type T. For me the reason was, namespace was not included in the top of file.

    using System.Collections; 
    

    After adding the namespace it was fine for me.

    0 讨论(0)
提交回复
热议问题