我有一个对象数组,我通过索引找到项目,分配一个值,但然后查看数组,该项目没有显示更新的值。
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
答案 0 :(得分:3)
因为值类型被复制到所使用的任何地方 - 你正在更新check变量中的值类型的副本,而不是数组中的副本。
您需要更新数组中的副本:
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
当然,总是值得阅读Lippert先生的"The Truth About Value Types"
答案 1 :(得分:1)
Dim cheque As Cheque = chequeColl(idx)
cheque.Amount = Amount
使用:
chequeColl(idx).Amount = Amount
它是如何运作的?