为什么List<T>声明GetEnumerator()和IEnumerable<T>.GetEnumerator()?

3

为什么List定义了这三个方法?

    public Enumerator GetEnumerator()
        => new Enumerator(this);

    IEnumerator<T> IEnumerable<T>.GetEnumerator()
        => new Enumerator(this);

    IEnumerator IEnumerable.GetEnumerator()
        => new Enumerator(this);

他们都在做同样的事情。只需要这个就足够了:

public Enumerator GetEnumerator()
        => new Enumerator(this);

2
https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/interfaces/explicit-interface-implementation - Tim Schmelter
1
Enumerator GetEnumerator() lets it return a struct enumerator for use in foreach loops, without allocating. IEnumerator<T> IEnumerable<T>.GetEnumerator() lets it implement the IEnumerator<T> GetEnumerator() method from the IEnumerable<T> interface, so you can do IEnumerable<T> x = new List<T>(); foreach (var item in x) ... - canton7
1个回答

7

Wouldn't it be enough to just have this:

public Enumerator GetEnumerator()
       => new Enumerator(this);
不会,因为这样不会实现IEnumerable<T>IEnumerable接口,其中GetEnumerator()方法的返回类型分别为IEnumerator<T>IEnumerator
必须匹配返回类型才能实现接口。
确实,您可以轻松地进行测试:
using System.Collections;
using System.Collections.Generic;

public class MyList<T> : IEnumerable<T>
{
    public Enumerator GetEnumerator() =>
        new Enumerator();

    // Implement this fully so we can concentrate on IEnumerable<T>
    public struct Enumerator : IEnumerator<T>
    {
        public T Current => default;
        object IEnumerator.Current => default;
        public bool MoveNext() => true;
        public void Reset() {}
        public void Dispose() {}
    }
}

这会产生以下错误:

  • 错误 CS0738:“MyList<T>”未实现接口成员“IEnumerable<T>.GetEnumerator()”。“MyList<T>.GetEnumerator()”无法实现“IEnumerable<T>.GetEnumerator()”,因为它没有匹配的返回类型“IEnumerator<T>”。
  • 错误 CS0738:“MyList<T>”未实现接口成员“IEnumerable.GetEnumerator()”。“MyList<T>.GetEnumerator()”无法实现“IEnumerable.GetEnumerator()”,因为它没有匹配的返回类型“IEnumerator”。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接