2013-09-24 117 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 

當您指向同一對象並修改其屬性時,屬性的值將發生變化。