C#通用IEnumerable

时间:2018-11-29 09:31:31

标签: 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();
    }
}

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

我确实知道IEnumerable<T>继承自IEnumerator,所以我必须同时实现这两者。

除此之外,当曾经使用非通用接口时,我很困惑。在调试中,它永远不会输入。有人可以帮我理解吗?

1 个答案:

答案 0 :(得分:7)

  

我对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);
}

也只有少数LINQ方法可以调用它:CastOfType

var castCollection = new MyGenericCollection().OfType<int>();