简体   繁体   中英

'Yield' in either IEnumerator or IEnumerable?

I've been Searching for this point and i do not get any information about it yet!.

I Saw a lot a videos and red bunch of articles about 'Yield Return' and i think i've better understanding about it but there is a point I can't get it

What is the Correct interface should i use yield return into it ? (of Course Yield return will be used in Loop but in which interface).

I mean there is variation in this point, I saw some of people creating an "iterator" within IEnumerator , for example :

static string[] Names = { "Name1", "Name2", "Name3" };

    static IEnumerator Test()
    {
        for (int i = 0; i < Names.Length; i++)
        {
            yield return Names[i];
        }
    }

and Some others use IEnumerable :

        static IEnumerable Test()
    {
        for (int i = 0; i < Names.Length; i++)
        {
            yield return Names[i];
        }
    }

I'm assuming it's better to Create an "Iterator" using "Yield return" within IEnumerable interface, because In general IEnumerable responsible of having access to the class (to be more accurate, it returns an instance of the class(Object)) that defend the Logic of iteration. and which exactly what happen by the compiler (the sugar of yield Keyword) in this case.

 private static IEnumerable Test() => new <Test>d__1(-2);
//decompiled code of Test() method above Using reflector tool

Any Ideas about this ?

The compiler supports both, and actually if the return value is IEnumerable<T> , the generated class will implement both interfaces where GetEnumerator() is implemented something like this (roughly):

IEnumerator<T> IEnumerable<T>.GetEnumerator()
{
    if (state == Created && initialThreadId == Environment.CurrentManagedThreadId)
    {
        state = EnumerationStarted;
        return this;
    }
    else
        return new GeneratedEnumerableEnumerator(state: EnumerationStarted);
}

state in the code above is an int , Created and EnumerationStarted are not real constant names. state can have many inner values depending on the complexity of your implementation.

What is the Correct interface should i use yield return

It depends on your case. If you implement the IEnumerable<T>.GetEnumerator() in your custom collection type use IEnumerator<T> . And if you need to return an IEnumerable<T> , whose content can be easily yielded, then use IEnumerable<T> . Both can make sense.

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