C#Generic IEnumerable

Bir*_*man 2 c# ienumerable ienumerator

我正在学习引擎盖下的迭代器模式,所以最终我可以在某些类中使用它.这是一个测试类:

public class MyGenericCollection : IEnumerable<int>
{
    private int[] _data = { 1, 2, 3 };

    public IEnumerator<int> GetEnumerator()
    {
        foreach (int i in _data)
        {
            yield return i;
        }
    }
    IEnumerator IEnumerable.GetEnumerator()
    {
        return GetEnumerator();
    }
}
Run Code Online (Sandbox Code Playgroud)

我对这IEnumerable.GetEnumerator()部分很困惑.在我运行的代码测试中,它从未被引用或使用,但我必须让它来实现泛型IEnumerable.

我确实理解IEnumerable<T>继承自IEnumerator,所以我必须实现两者.

除此之外,当使用非通用接口时我很困惑.在调试中它永远不会进入.谁能帮我理解?

Jon*_*eet 8

我对IEnumerable.GetEnumerator()部分感到困惑.在我运行的代码测试中,它从未被引用或使用过,但我必须让它来实现通用的IEnumerable.

任何使用你的类型的东西都可以使用它IEnumerable.例如:

IEnumerable collection = new MyGenericCollection();
// This will call the GetEnumerator method in the non-generic interface
foreach (object value in collection)
{
    Console.WriteLine(value);
}
Run Code Online (Sandbox Code Playgroud)

只有一些LINQ方法也可以调用它:CastOfType:

var castCollection = new MyGenericCollection().OfType<int>();
Run Code Online (Sandbox Code Playgroud)