为什么我不能枚举这个集合中的项目:?

时间:2011-04-13 14:40:48

标签: .net vb.net

对象数组是否可枚举?

在代码中查找注释

Public Class AddressCollection

    Inherits System.Collections.ObjectModel.Collection(Of AddressType)

    Public Sub New()

    End Sub

    Public Sub New(ByVal ParamArray addressTypeArray() As AddressType)

        For Each currentAddress As AddressType In Me

            If currentAddress IsNot Nothing Then '<<<<--NEVER HITS THIS LINE
                Me.Add(currentAddress)
            End If
        Next

        For i As Integer = 0 To addressTypeArray.Count - 1

            Dim currentAddress As AddressType = addressTypeArray(i) '<<< BUT IT DOES HIT THIS LINE

            If currentAddress IsNot Nothing Then
                Me.Add(currentAddress)
            End If

        Next

    End Sub

3 个答案:

答案 0 :(得分:8)

我想你想要:

For Each currentAddress As AddressType In addressTypeArray

..匹配相当于:

For i As Integer = 0 To addressTypeArray.Count - 1

答案 1 :(得分:7)

他们这样做。但是你不想迭代addressTypeArray,而不是Me吗?我想,Me在构造函数中仍然是空的,这就是为什么你从不打线。

干杯,马蒂亚斯

答案 2 :(得分:2)

为什么要这样?您位于班级的构造函数中,并且没有对象添加到您的类所代表的集合中...要验证这一点,请在第一个Me.Count之前检查For Each的结果。它将为0.我想,你真的想迭代提供的参数addressTypeArray