VB.NET中实现IEnumerator接口

王朝vb·作者佚名  2006-01-09
宽屏版  字体: |||超大  

VB.NET中实现IEnumerator接口

在面向对象的设计中,经常会用到有类似父子关系的这个对象,比如在我现在的一个项目中,有订单对象,在一个订单下又包含多个产品,这时我就想用Iterator模式来封装订单下的产品,在dot Net中的IEnumerator接口就是用来实现迭代的,来支持dot Net中的for each的操作。

要实现IEnumerator接口,需在实现以下几个函数来支持IEnumerator接口的操作

Overridable ReadOnly Property Current() As Object

Current用于在迭代过程中得到当前的对象

Public Overridable Function MoveNext() As Boolean

MoveNext用于在迭代过程中将迭代指针指向下一个对象,初始是迭代指针指向集合的开始(在第一个节点之前的位置),一旦越过集合的结尾,在调用 Reset 之前,对 MoveNext 的后续调用返回 false。

Overridable Sub Reset()

将枚举数设置为其初始位置,该位置位于集合中第一个元素之前。

只要集合保持不变,枚举数就将保持有效。如果对集合进行了更改(例如添加、修改或删除元素),则该枚举数将失效且不可恢复,并且下一次对 MoveNext 或 Reset 的调用将引发 InvalidOperationException

下需是一个具体的实现IEnumerator接口的对像

'------------------------实现IEnumerator接口的类----------------------------------

Imports System.Collections

'在此实际实现的是System.Collections.IEnumerable接口,IteratorProduct 用此接口来向使用者提供对IEnumerator接口的操作。

Public Class IteratorProduct : Implements System.Collections.IEnumerable

Private Products As Collection '用Collection在存订单中的所有产品

Private item As Integer = -1

Public Sub New()

Products = New Collection

Products.Add("xh") '这只是为了测试方便,将加入产品的内容直接写在这了

Products.Add("lj")

Products.Add("qd")

End Sub

Overridable ReadOnly Property Current() As Object

Get

Return Products(item)

End Get

End Property

Public Overridable Function MoveNext() As Boolean

item += 1

End Function

Overridable Sub Reset()

item = -1

End Sub

' 返回迭代对像给使用者

Overridable Function GetEnumerator() As IEnumerator Implements IEnumerable.GetEnumerator

Return Me.Products.GetEnumerator

End Function

End Class

'------------------------使用类----------------------------------

Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

Dim Products As IteratorProduct

Products = New IteratorProduct

Dim ProductName As String

For Each ProductName In Products

Response.Write(ProductName)

Response.Write("<br>")

Next

End Sub

输出为:

xh

lj

qd

说明实现成功

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
© 2005- 王朝网络 版权所有