IEnumerable and IEnumerator in the same class, bad idea?

房东的猫 提交于 2021-01-27 04:44:11

问题


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?


回答1:


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



回答2:


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 :)




回答3:


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.



来源:https://stackoverflow.com/questions/2519168/ienumerable-and-ienumerator-in-the-same-class-bad-idea

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!