在VB.NET编程中实现IEnumerator接口

作者:互联网   出处:控件中国网   2014-11-05 19:19:47   阅读:1

VB.NET经过长时间的发展,很多用户都很了解VB.NET实现IEnumerator接口了,这里我发表一下个人理解,和大家讨论讨论。在面向对象的设计中,经常会用到有类似父子关系的这个对象,比如在我现在的一个项目中,有订单对象,在一个订单下又包含多个产品,这时我就想用 Iterator模式来封装订单下的产品,在dot Net中的IEnumerator接口就是用来实现迭代的,来支持dot Net中的for each的操作。

  要VB.NET实现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。

  下需是一个具体的VB.NET实现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 

Copyright© 2006-2015 ComponentCN.com all rights reserved.重庆磐岩科技有限公司(控件中国网) 版权所有 渝ICP备12000264号 法律顾问:元炳律师事务所
客服软件
live chat