2013-09-24 76 views
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时更改可变数据。

+0

为什么不使用['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

回答

0

即使您在对象上使用了ByVal,对象的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 

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