这不是一道作业题,尽管情境很离奇。我只是为了简化例子而替换了我正在使用的真实对象。这里有一个链接可以帮助你入门:This,但我不确定该如何继续。 我正在尝试编写一个包含集合的类,并且我在
IEnumerator
和IEnumerable
的世界中迷失了方向,这是我很新的领域(甚至不确定我是否走上了正确的道路)。假设我有一个类:Public Class BakedBean
Private Shape As String
Private Variety As String
Private Flavour As String
'etc
End Class
还有一个表示一组 BakedBean
的类:
Public Class TinOfBeans
'?
End Class
我希望能够在 TinOfBeans
类中以集合的形式获取 Beans
,这样我就可以进行一些调用,但不必绑定到特定的集合类型:
Dim myTin As New TinOfBeans()
myTin.Add(New BakedBean(...))
For Each bean As BakedBean in myTin
'...
Next
myTin(0).Flavour = "beany"
我一直在研究IEnumerable
和IEnumerator
,目前已经了解了这么多,但我现在非常迷茫:
BakedBean类
Public Class BakedBean
Private Shape As String
Private Variety As String
Private Flavour As String
'etc
End Class
BeansEnumerator 类
Public Class BeansEnumerator
Implements IEnumerator
Private Position As Integer = -1
Public ReadOnly Property Current As Object Implements System.Collections.IEnumerator.Current
Get
'???
End Get
End Property
Public Function MoveNext() As Boolean Implements System.Collections.IEnumerator.MoveNext
'???
End Function
Public Sub Reset() Implements System.Collections.IEnumerator.Reset
Position = -1
End Sub
End Class
TinOfBeans类
Public Class TinOfBeans
Implements IEnumerable
Private beansEnum As BeansEnumerator
Public Function GetEnumerator() As System.Collections.IEnumerator Implements System.Collections.IEnumerable.GetEnumerator
Return beansEnum
End Function
End Class
目前为止,我已经陷入了困境,不知道该怎么继续下去(或者,正如我一开始所说的那样,这是否是正确的方法)。有什么建议吗?
TinOfBeans
类中添加一个Private beans As List(Of BakedBeans)
,并通过属性公开它,但那样我就永远被绑定到了一个List
上。如果我以后需要将其更改为Dictionary
或其他什么(世界需要更多的豆子字典!),我就有破坏所有涉及它的代码的风险。我不能完全放弃TinOfBeans
类并用List(Of BakedBeans)
替换整个类,因为它将具有List
没有的其他方法(例如Cook()
)。 - Kai