vb.net奇怪的传参数特性。ByVal传入的参数会被修改?
vb.net吧
全部回复
仅看楼主
level 1
lity2k 楼主
描述:
先定义一个二维数组map(x,y)
然后把map传入一个子过程(子函数也一样) test(ByVal arr(,) As Integer)
在子过程中对传入参数arr 进行任何的赋值、修改都会直接影响子过程外的map变量。
求原因,解决办法。
环境:vs2013
类型:windows 窗口程序
测试框架:framework2 framework4
界面控件:textbox1、textbox2、button1
代码:
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim t As New test
Dim map(,) As Integer = t.str2map(Me.TextBox1.Text)
For x As Integer = 0 To map.GetUpperBound(0)
Dim line As String = ""
For y As Integer = 0 To map.GetUpperBound(1)
line = line & New Point(x, y).ToString & ":" & map(x, y) & ","
Dim map_temp(,) As Integer = map
t.test(map_temp)
Next
Me.TextBox2.AppendText(line & vbCrLf)
Next
End Sub
End Class
Class test
Public Function test(ByVal arr(,) As Integer) As Integer
For x As Integer = 0 To arr.GetUpperBound(0)
For y As Integer = 0 To arr.GetUpperBound(1)
arr(x, y) = 0
Next
Next
Return 0
End Function
Public Function str2map(ByVal str As String) As Integer(,)
Dim map(,) As Integer
Dim lines() As String = str.Trim.Split(vbCrLf)
Dim x, y As Integer
x = 0
y = lines.GetUpperBound(0)
ReDim Preserve map(y, x)
For y_index As Integer = 0 To y
Dim line As String = lines(y_index).Trim
Dim values() As String = line.Split(",")
x = values.GetUpperBound(0)
If x > map.GetUpperBound(1) Then ReDim Preserve map(y, x)
For x_index As Integer = 0 To x
If IsNumeric(values(x_index)) Then _
map(y_index, x_index) = values(x_index)
Next
Next
Return map
End Function
End Class
2015年01月14日 09点01分 1
level 4
传入的是数组地址,地址按值传过去,当然会修改数组元素值了。
2015年01月14日 15点01分 2
1