IEnumerable 和 IEnumerator 在同一个类中,不是个好主意吗?
这是一个坏主意吗?
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
绝对是个坏主意。特别是,这意味着对
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 :)
这是一个坏主意,因为如果有人尝试同时多次枚举您的集合,该解决方案将会崩溃。
例如:这会以某种方式破坏
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
来自实现 IEnumerable:
顺便说一句,该网站由 Brad Abrams 维护,他是 的作者之一框架设计指南.
From Implementing IEnumerable:
By the way, this website is maintained by Brad Abrams - one of the authors of Framework Design Guidelines.