.NET开发

本类阅读TOP10

·NHibernate快速指南(翻译)
·vs.net 2005中文版下载地址收藏
·【小技巧】一个判断session是否过期的小技巧
·VB/ASP 调用 SQL Server 的存储过程
·?dos下编译.net程序找不到csc.exe文件
·通过Web Services上传和下载文件
·学习笔记(补)《.NET框架程序设计(修订版)》--目录
·VB.NET实现DirectDraw9 (2) 动画
·VB.NET实现DirectDraw9 (1) 托管的DDraw
·建站框架规范书之——文件命名

分类导航
VC语言Delphi
VB语言ASP
PerlJava
Script数据库
其他语言游戏开发
文件格式网站制作
软件工程.NET开发
VB.NET中实现IEnumerator接口

作者:未知 来源:月光软件站 加入时间:2005-5-13 月光软件站

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
说明实现成功




相关文章

相关软件