简体   繁体   English

ByVal在VB.NET中无法正常工作

[英]ByVal does work not correctly in VB.NET

I have a code in VB.NET like this: 我在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

When I run this code, in the btnProcess event click, variable "data" is array = {3,5,1}. 当我运行此代码时,在btnProcess事件中单击,变量“数据”为array = {3,5,1}。 By SelectionSort(data) procedure, variable data is changed. 通过SelectionSort(data)过程,可以更改变量数据。 Item in variable data have sorted by that procedure, so when SelectionSortNewList(data) is run, array "data" have sorted became {1,3,5}. 变量数据中的项目已通过该过程进行了排序,因此当运行SelectionSortNewList(data)时,数组“数据”已排序为{1,3,5}。 Why does it happen? 为什么会发生?

Although I have used "Byval parameter" in SelectionSort and SelectionSortNewList, I don't want variable data to be changed when it pass to SelectionSort. 尽管我在SelectionSort和SelectionSortNewList中使用了“ Byval参数”,但我不希望将变量数据传递给SelectionSort时对其进行更改。

Even if you use a ByVal on an object, the properties of the object can be modified. 即使在对象上使用ByVal ,也可以修改对象的properties

The instance of the object cannot be modified but not its properties. 对象的实例不能修改,但其属性不能修改。

Example: 例:

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

If I pass the class as ByVal; 如果我将类作为ByVal通过;

Private sub Test(ByVal MyCar as Car)

MyCar.Make = "BMW"

End Sub

The value of the property will change as you're pointing to the same object and modifying its property. 当您指向同一对象并修改其属性时,该属性的值将更改。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM