开发者

Why does implementing 'IList<T>' require defining two 'GetEnumerator' methods?

When I implement IList<T>, I find that I am required to define two GetEnumerator methods. One returns a value that is of type IEnumerator, while the other returns IEnumerator<T>.

I'm a little confused about the difference between these two GetEnumerator methods. While the return types are obviously different, don't they essentially hold the same data?

In addition, why is it that both versions of GetEnumerator can exist as methods when they differ only by return type? This seems to violate the rule in C# which s开发者_如何学编程pecifies that overloaded methods cannot differ only by return type.


Both should return the same data, yes.

IEnumerator is from .Net v1.1, before generic typing was introduced. IEnumerator<T> is the generically typed version added in .Net v2.

The "old" version, IEnumerator, has been kept for compatibility, so now IList<T> implements both.

The difference between the two is that the non-generic IEnumerator returns object's whereas the generic IEnumerator<T> returns T's. Although, the c# compiler will insert a cast for you to make the non-generic IEnumerator seem strongly-typed when used in a foreach.

The presence of a generic type argument is enough for the compiler to differentiate between the two interfaces, but for a class to implement both one must be explicitly implemented.


The two come from separate interfaces that IList itself implements, which is why you have to implement both:

public interface IList<T> : ICollection<T>, IEnumerable<T>, IEnumerable

And they're both able to exist because of Explicit Interface Implementation.


Yes, both methods should return the same data.

They can co-exist because they are part of two different interfaces, IEnumerable and IEnumerable<T>.


They both can exist because one of them will be implemented explicitly:

IEnumerator IEnumerable.GetEnumerator()
{

}

If you attempt to make them both implicitly defined, you will get compile errors.

Yes, they should both return the same data.

You are required to define the two versions of GetEnumerator in order to satisfy both interfaces (IEnumerable and IEnumerable<T>) from which IList<T> is derived. In practice, however, you tend to find the non-generic version of GetEnumerator just calls the generic one in most implementations.


IList<T> Implements both IEnumerable<T> and IEnumerable. The different implementations of GetEnumerator come from each of these interfaces. Both should return the same data.


IEnumerator enumerates objects, whereas IEnumerator enumerates T. For your second question, the second function is fully qualified:

  System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()  
  {

  }

vs

public IEnumerator<T> GetEnumerator()
    {

    }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜