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オブジェクトにを使用しても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 に答える