简体   繁体   中英

C# Generic IEnumerable

I'm learning about the iterator pattern under the hood so eventually I can use it in some classes. Here's a test class:

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

I'm confused on the IEnumerable.GetEnumerator() section. In the code tests that I've ran, it's never referenced or used, but I have to have it to implement the generic IEnumerable .

I do understand that IEnumerable<T> inherits from IEnumerator , so that I have to implement both.

Outside of that I'm confused when the non-generic interface is ever used. In debugging it's never entered. Can anyone help me understand?

I'm confused on the IEnumerable.GetEnumerator() section. In the code tests that I've ran, it's never referenced or used, but I have to have it to implement the generic IEnumerable.

It would be used by anything that used your type as just an IEnumerable . For example:

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

There are just a few LINQ methods that would call it, too: Cast and OfType :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM