1

我在 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 时被更改。

4

1 回答 1

0

即使您ByVal在对象上使用 a ,properties也可以修改对象的 。

不能修改对象的实例,但不能修改其属性。

例子:

Public Class Cars

    Private _Make As String
    Public Property Make() As String
        Get
            Return _Make
        End Get
        Set(ByVal value As String)
            _Make = value
        End Set
    End Property

End Class

如果我以 ByVal 的身份通过课程;

Private sub Test(ByVal MyCar as Car)

MyCar.Make = "BMW"

End Sub

当您指向同一个对象并修改其属性时,该属性的值将发生变化。

于 2013-09-24T08:09:55.103 回答