1
我有这样在VB.NET代码:BYVAL不工作不正确地在VB.NET
' This code will sort array data
Public Sub SelectionSort(ByVal array as ArrayList)
For i as Integer = 0 To array.Count -1
Dim index = GetIndexMinData(array, i)
Dim temp = array(i)
array(i) = array(index)
array(index) = temp
Next
End Sub
Public Function GetIndexMinData(ByVal array As ArrayList, ByVal start As Integer) As Integer
Dim index As Integer
Dim check As Integer = maxVal
For i As Integer = start To Array.Count - 1
If array(i) <= check Then
index = i
check = array(i)
End If
Next
Return index
End Function
' This code will sort array data
Public Sub SelectionSortNewList(ByVal array As ArrayList)
Dim temp As New ArrayList
' Process selection and sort new list
For i As Integer = 0 To array.Count - 1
Dim index = GetIndexMinData(array, 0)
temp.Add(array(index))
array.RemoveAt(index)
Next
End Sub
Private Sub btnProcess_Click(sender As System.Object, e As System.EventArgs) Handles btnProcess.Click
Dim data as new ArrayList
data.Add(3)
data.Add(5)
data.Add(1)
SelectionSort(data)
SelectionSortNewList(data)
End Sub
当运行该代码,在btnProcess事件点击,可变的“数据”是数组= { 3,5,1}。通过SelectionSort(数据)过程,变量数据被改变。变量数据中的项目已按该过程排序,因此在运行SelectionSortNewList(data)时,数组“data”已排序为{1,3,5}。为什么会发生?
尽管我在SelectionSort和SelectionSortNewList中使用了“Byval参数”,但我不想在传递给SelectionSort时更改可变数据。
为什么不使用['Sort'](http://msdn.microsoft.com/en-us/library/8k6e334t.aspx)方法?其次,我会去[[List(Of T)'](http://msdn.microsoft.com/en-us/library/6sh2ey19.aspx)(在这种情况下,T = Integer),而不是一个ArrayList,因为它在编译时是安全的。最后,我建议研究**值类型**和**参考类型**之间的区别,了解其差异非常重要。 – Styxxy