0

我一直在研究 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
4

2 回答 2

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,它将继续循环遍历数组并初始化其余部分。

于 2013-06-05T18:01:19.913 回答
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;你在哪里创建对象;循环在哪里?(这些代码片段是否在不同的模块/类模块/函数中?)

于 2013-06-04T14:05:18.943 回答