Enumerator Implementation: Use struct or class?

前端 未结 8 2605
再見小時候
再見小時候 2021-02-19 17:44

I noticed that List defines its enumerator as a struct, while ArrayList defines its enumerator as a class. What\'s t

8条回答
  •  鱼传尺愫
    2021-02-19 18:17

    To expand on @Earwicker: you're usually better off not writing an enumerator type, and instead using yield return to have the compiler write it for you. This is because there are a number of important subtleties that you might miss if you do it yourself.

    See SO question "What is the yield keyword used for in C#?" for some more details on how to use it.

    Also Raymond Chen has a series of blog posts ("The implementation of iterators in C# and its consequences": parts 1, 2, 3, and 4) that show you how to implement an iterator properly without yield return, which shows just how complex it is, and why you should just use yield return.

提交回复
热议问题