Enumerator Implementation: Use struct or class?

前端 未结 4 862
我在风中等你
我在风中等你 2021-02-19 17:46

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

相关标签:
4条回答
  • 2021-02-19 18:15

    An enumerator is inherently a changing structure, since it needs to update internal state to move on to the next value in the original collection.

    In my opinion, structs should be immutable, so I would use a class.

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

    Like this others, I would choose a class. Mutable structs are nasty. (And as Jared suggests, I'd use an iterator block. Hand-coding an enumerator is fiddly to get right.)

    See this thread for an example of the list enumerator being a mutable struct causing problems...

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

    Reason List uses a struct enumerator is to prevent garbage generation in foreach statements. This is pretty good reason especially if you are programming for Compact Framework, because CF doesn't have generational GC and CF is usually used on low performance hardware where it can quickly lead to performance issues.

    Also, I don't think mutable structs are source of problems in examples some posted, but programmers that don't have good understanding of how value types work.

    0 讨论(0)
  • 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)
提交回复
热议问题