开发者

IEnumerable and IEnumerator in the same class, bad idea?

开发者 https://www.devze.com 2022-12-24 08:59 出处:网络
Is this a bad idea? Private Class GH_DataStructureEnumerator(Of Q As Types.IGH_Goo) Implements IEnumerable(Of Q)

Is this a bad idea?

Private Class GH_DataStructureEnumerator(Of Q As Types.IGH_Goo)
  Implements IEnumerable(Of Q)
  Implements IEnumerator(Of Q)
  ....
  ....
  'Current, MoveNext, Reset etc.'
  ....
  ....

  Public Function GetEnumerator_Generic() As IEnumerator(Of Q) _
                  Implements IEnumerable(Of Q).GetEnumerator
    Return Me
  End Function
End Class

This class is only visible as an IEnumerable(Of T) readonly property, and it saves me an additional class that wraps IEnumerator(Of T)开发者_如何学编程. But somehow it just seems wrong. Is there a better way?


Definitely a bad idea. In particular, it means that two calls to GetEnumerator will return references to the same object - when they should return independent iterators.

Now having said that, the C# compiler will generate classes which implement both types if you use iterator blocks... but it goes to great lengths to make sure that it gets it right. I suggest you don't put yourself through that pain :)


This is a bad idea because the solution will break down if someone attempts to enumerate your collection more than once at the same time.

For example: This will break in some way

For Each cur1 in yourObj 
  For Each cur2 in yourObj
    Console.WriteLine("{0} - {1}", cur1,cur2)
  Next
Next


From Implementing IEnumerable:

Do provide a GetEnumerator() method that returns a nested public struct called “Enumerator”.

By the way, this website is maintained by Brad Abrams - one of the authors of Framework Design Guidelines.

0

精彩评论

暂无评论...
验证码 换一张
取 消