考虑VB中的以下代码:
Dim speed() As Integer = {0, 1, 2, 3, 4}
Dim speed2() As Integer
speed2 = speed
For i = 0 To UBound(speed2)
speed2(i) *= 2
Next
Dim str As String
For i = 0 To UBound(speed)
str &= speed(i)
Next
For i = 0 To UBound(speed2)
str &= speed2(i)
Next
Console.WriteLine(str)
对于此代码,答案应该是: 12342468
但真正出现的是: 24682468
有谁知道代码有什么问题,或者为什么数组“速度”正在改变它的值?
答案 0 :(得分:3)
数组speed
更改其值,因为数组是引用类型
像在行
speed2 = speed
使数组speed2
引用保留speed
值的相同内存位置。
因此,在执行计算时,分配会影响speed
答案 1 :(得分:1)
这样做应该解决它
Dim speed() As Integer = {0, 1, 2, 3, 4}
Dim speed2() As Integer
ReDim speed2(speed.GetUpperBound(0))
Array.Copy(speed, 0, speed2, 0, speed.GetUpperBound(0) + 1)