タグ:

For Each を実装する

クラスを作っているとFor Each文を使用したい時がありますよね。そんな時はIEnumeratorインターフェースを定義します。

サンプルコード

Public Class Parson
  Public Property Name As String
  Public Property Age As Integer
End Class

Public Class ParsonList
  Implements IEnumerable

  Private list(5) As Parson

  Public Sub New()
    Dim i As Integer

    For i = 0 To 5
      list(i) = New Parson() With {.Age = i, .Name = "Name" & i.ToString("000")}
    Next
  End Sub


  Public Function GetEnumerator() As IEnumerator _
    Implements IEnumerable.GetEnumerator
    Return New MyEnumerator(list)
  End Function
End Class

Public Class MyEnumerator
  Implements IEnumerator

  Private pointer As Integer = -1
  Dim list() As Parson

  Public Sub New(obj As Parson())
    pointer = -1
    list = obj
  End Sub

  Public Function MoveNext() As Boolean _
    Implements IEnumerator.MoveNext
    pointer += 1
    Return (pointer < list.Length)
  End Function

  Public Sub Reset() _
    Implements IEnumerator.Reset
    pointer = -1
  End Sub

  Public ReadOnly Property Current() As Object _
    Implements IEnumerator.Current
    Get
      Return list(pointer)
    End Get
  End Property
End Class

Sub Main()
  Dim ps As New ParsonList()
  For Each p As Parson In ps
    Console.Write("Age:=" & p.Age)
    Console.WriteLine("Name:=" & p.Name)
  Next
  Console.ReadLine()

End Sub

IEnumerableではGetEnumeratorを、IEnumeratorではMoveNext, Reset, Currentをそれぞれ実装する必要があります。