什么东西设置为Nothing后它保持原样?

时间:2012-10-23 18:17:30

标签: vb.net nothing

我有以下内容:

For Each curCustomer As Customer In _customersEdit
    If (IsNothing(curCustomer)) Then
        Continue For
    End If
    'other code
    If (curCustomer.SeatIDs(0) = primarySeat) Then
        'other code
    End If

    If (curCustomer.SeatIDs.Count = 0) Then
        curCustomer = Nothing
    End If
Next

运行此代码一旦没问题,当你第二次运行它时虽然我在检查它是否是主要座位时出错,因为SeatIDs是Nothing。当我在curCustomer上设置一个断点= Nothing它第一次触发时,我将客户名称更改为“test”,在下一行放置一个断点,它确实将curCustomer设置为没有它应该具有的。接下来,当我再次运行代码时,它会在检查主席位时抛出错误,并且curCustomer仍然存在我给它的“测试”名称,然后再将其设置为Nothing。为什么会这样?

2 个答案:

答案 0 :(得分:2)

curCustomer = Nothing实际上没有做任何事情(在示例中),因为curCustomer在下一个for-each序列中被重新初始化,而curCustomer函数仅作为参考(你将数组中对项的引用归零,而不是数组项本身。

您需要使用索引在数组_customersEdit中将其设置为空。

你可以这样做:

    Dim i As Integer
    For i = 0 To _customersEdit.Count - 1
        ' your check code
        If (curCustomer.SeatIDs.Count = 0) Then
            _customerEdit(i) = Nothing
        End If

    Next

或者可能更好:

    Dim i As Integer
    For i =  _customersEdit.Count - 1 To 0 Step -1
        ' your check code
        If (curCustomer.SeatIDs.Count = 0) Then
            _customerEdit.RemoveAt(i)
        End If
    Next

答案 1 :(得分:0)

_customersEdit(i) = Nothing会将数组中的引用设置为Nothing。