Why isn't my item in an array getting updated?
I have an array of objects, I find the it开发者_JAVA百科em by index, assign a value but then looking at the array the item doesn't show the updated value.
Public Structure Cheque
Public Id As String
Public Status As Byte
Public Amount As String
Public WarrantNo As String
End Structure
Public Class ChequeCollection
Private chequeColl() As Cheque 'This is populated ok
Public Sub UpdateChequeAmount(ByVal Id As String, ByVal Amount As String)
SyncLock lockObject
Dim idx As Integer = Get_idx(Id) 'Finds it ok
If idx <> -1 Then
Dim cheque As Cheque = chequeColl(idx)
cheque.Amount = Amount 'Updates value ok but if you look in chequeColl the value isn't there
End If
End SyncLock
End Sub
End Class
Because value types are copied everywhere they're used - you're updating your copy of the value type that's in the cheque variable, as opposed to the copy within the array.
You'd need to update the copy in the array:
Dim cheque As Cheque = chequeColl(idx)
cheque.Amount = Amount 'Updates value ok but if you look in chequeColl the value isn't there
chequeColl(idx) = cheque
And of course, always worth reading "The Truth About Value Types" by Mr. Lippert
Dim cheque As Cheque = chequeColl(idx)
cheque.Amount = Amount
with:
chequeColl(idx).Amount = Amount
how does it work then ?
精彩评论