我在 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(data) 过程,变量数据被改变。变量数据中的项目已按该过程排序,因此当运行 SelectionSortNewList(data) 时,数组“数据”已排序为 {1,3,5}。为什么会这样?
虽然我在 SelectionSort 和 SelectionSortNewList 中使用了“Byval 参数”,但我不希望变量数据在传递给 SelectionSort 时被更改。