IEnumerable 和 IEnumerator 在同一个类中,不是个好主意吗?

发布于 2024-08-26 18:40:09 字数 492 浏览 6 评论 0原文

这是一个坏主意吗?

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

此类仅作为 IEnumerable(Of T) 只读属性可见,它为我节省了一个包装 IEnumerator(Of T) 的附加类。但不知何故,这似乎是错误的。有更好的办法吗?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

二货你真萌 2024-09-02 18:40:09

绝对是个坏主意。特别是,这意味着对 GetEnumerator 的两次调用将返回对同一对象的引用 - 当它们应该返回独立迭代器时。

话虽如此,如果您使用迭代器块,C# 编译器将生成实现这两种类型的类……但它会竭尽全力确保它正确。我建议你不要让自己经历这种痛苦:)

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

命比纸薄 2024-09-02 18:40:09

这是一个坏主意,因为如果有人尝试同时多次枚举您的集合,该解决方案将会崩溃。

例如:这会以某种方式破坏

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

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
倾其所爱 2024-09-02 18:40:09

来自实现 IEnumerable

一定要提供一个 GetEnumerator() 方法,该方法返回一个名为“Enumerator”的嵌套公共结构

顺便说一句,该网站由 Brad Abrams 维护,他是 的作者之一框架设计指南.

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文