Enumerator Implementation: Use struct or class?

前端 未结 8 2648
再見小時候
再見小時候 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:19

    The easiest way to write an enumerator in C# is with the "yield return" pattern. For example.

    public IEnumerator<int> Example() {
      yield return 1;
      yield return 2;
    }
    

    This pattern will generate all of the enumerator code under the hood. This takes the decision out of your hands.

    0 讨论(0)
  • 2021-02-19 18:19

    Write it using yield return.

    As to why you might otherwise choose between class or struct, if you make it a struct then it gets boxed as soon as it is returned as an interface, so making it a struct just causes additional copying to take place. Can't see the point of that!

    0 讨论(0)
提交回复
热议问题