VB.NET中实现IEnumerator接口

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()
 将枚举数设置为其初始位置,该位置位于集合中第一个元素之前。

只要集合保持不变,枚举数就将保持有效。如果对集合进行了更改(例如添加、修改或删除元素),则该枚举数将失效且不可恢复,并且下一次对 MoveNextReset 的调用将引发 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
说明实现成功

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值