检查数组中的索引是否为空VB6

时间:2013-06-04 13:40:54

标签: arrays object vb6

我一直在研究VB6的一些面向对象的功能。我已经用Java做了很多OOP,我正试图让它工作:

我有一组Card个对象,我想检查是否已经创建了数组索引中的对象。

Dim cardsPlayer1(1 To 10) As Card

我创建了这样的对象:

Set cardsPlayer1(index) = New Card

如果尝试使用它测试我是否已将对象分配给索引:

For counter = 1 To 10
    If (cardsPlayer1(counter) Is Nothing) Then
        Set cardsPlayer1(counter) = New Card
    End If
Next counter

但它每次给我一个真正的价值并为整个数组创建一个新对象。

以下是相关代码:

'Jordan Mathewson
'May 31, 2013
Dim cardsPlayer1(1 To 10) As Card
Dim cardsPlayer2(1 To 10) As Card

Private Sub cmdStartGame_Click()
    Call addCard(1)
End Sub

'Called to add a card to one of the player's stacks
Private Sub addCard(player As Integer)
    Dim counter As Integer

    'To add a card to player1..
    If (player = 1) Then

        For counter = 1 To 10
            If (cardsPlayer1(counter) Is Nothing) Then
                Print "Object created." '<- Printed 10 times.
                Set cardsPlayer1(counter) = New Card
            End If
        Next counter

    'To add a card to player2..
    Else
        For counter = 1 To 10
            If (cardsPlayer2(counter) Is Nothing) Then
                Set cardsPlayer2(counter) = New Card
            End If
        Next counter

    End If

    Call refreshForm

End Sub

2 个答案:

答案 0 :(得分:1)

如果我理解正确的话,addCard子应该添加一张卡,但只需要调用一次就可以添加所有卡。这不是因为它无法分辨哪个数组元素是空的。这只是因为它在成功添加之后不会停止。

For counter = 1 To 10
    If (cardsPlayer1(counter) Is Nothing) Then
        Set cardsPlayer1(counter) = New Card
        Exit For ' <-- Add this
    End If
Next counter

如果没有Exit For,它将继续循环遍历数组并初始化其余部分。

答案 1 :(得分:0)

我怀疑你可能有一个范围问题。这给了我预期的结果:

Sub Test()
    Dim objectsArray(1 To 5) As TestObject

    If objectsArray(1) Is Nothing Then
        MsgBox "objectsArray(1) Is Nothing"    ' <----- displayed
    End If

    Set objectsArray(1) = New TestObject

    If objectsArray(1) Is Nothing Then
        MsgBox "objectsArray(1) Is Nothing"
    Else
        MsgBox "Not objectsArray(1) Is Nothing"    ' <----- displayed
    End If
End Sub

你在哪里声明objectsArray;你在哪里创建对象;循环在哪里? (这些代码片段是否在不同的模块/类模块/函数中?)