2

我有一个简单的类List.vb,如下所示:

Public Class List

    Public fList As List(Of Integer)
    Public Sub New()
        fList = New List(Of Integer)
        fList.Add(1)
        fList.Add(2)
        fList.Add(3)
        fList.Add(4)
        fList.Add(5)
    End Sub
End Class

Console应用程序正在使用此类,如下所示:

Module Module1

    Sub Main()

        Dim fObject As List = New List
        Dim cnt As Integer = 0
        For Each x As Integer In fObject.fList
            Console.WriteLine("hello; {0}", fObject.fList.Item(cnt).ToString())
            cnt = cnt + 1
        Next

        Console.WriteLine("press [enter] to exit")
        Console.Read()

    End Sub

End Module

我可以更改类代码以便 List.vb 是一个列表(整数)类型吗?
这意味着在控制台代码中我可以替换In fObject.fListIn fObject?
还是我在叫错树 - 类应该是单个对象而列表应该是类的集合?

4

2 回答 2

1

是的,你可以这么做。为了使对象与 兼容For Each,它必须具有以下GetEnumerator功能:

Public Function GetEnumerator() As IEnumerator _
  Implements IEnumerable.GetEnumerator
    Return New IntListEnum(fList)
End Function

IntListEnum反过来,该类必须实现,IEnumerator如下所示:

Public Class IntListEnum Implements IEnumerator

Private listInt As List(Of Integer)

Dim position As Integer = -1

Public Sub New(ByVal fList As List(Of Integer))
    listInt = fList
End Sub 

Public Function MoveNext() As Boolean Implements IEnumerator.MoveNext
    position = position + 1
    Return (position < listInt.Count)
End Function 

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

Public ReadOnly Property Current() As Object Implements IEnumerator.Current
    Get 
        Try 
            Return listInt(position)
        Catch ex As IndexOutOfRangeException
            Throw New InvalidOperationException()
        End Try 
    End Get 
End Property 

结束类

现在您可以设为私有,并按如下方式fList迭代您的:List

For Each x As Integer In fObject

你可以在这里看到一个完整的例子。

于 2012-12-08T12:14:55.957 回答
0

dasblinkenlight 提供的答案非常好,但如果您只需要一个预先填充的整数列表,您可以继承List(Of Integer)自然后让类在构造函数中填充自身:

Public Class List
    Inherits List(Of Integer)

    Public Sub New()
        Add(1)
        Add(2)
        Add(3)
        Add(4)
        Add(5)
    End Sub
End Class

当您从 继承时List(Of Integer),您的类会自动获得该类型实现的所有功能,因此您的类也成为一个以相同方式工作的列表类。然后,您可以像这样使用它:

Dim fObject As New List()
For Each x As Integer In fObject
    Console.WriteLine("hello; {0}", x)
Next
于 2012-12-08T16:40:23.073 回答