Enumerator Implementation: Use struct or class?

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

    Any implementation of IEnumerable should return a class. It may be useful for performance reasons to have a GetEnumerator method which returns a struct which provides the methods necessary for enumeration but does not implement IEnumerator; this method should be different from IEnumerable.GetEnumerator, which should then be implemented explicitly.

    Using this approach will allow for enhanced performance when the class is enumerated using a foreach or "For Each" loop in C# or vb.net or any context where the code which is doing the enumeration will know that the enumerator is a struct, but avoid the pitfalls that would otherwise occur when the enumerator gets boxed and passed by value.

提交回复
热议问题