如何通过值交换两个类,而不是引用?

时间:2018-12-22 02:07:38

标签: vb.net

ArrayList中有两个类。我想交换它们的所有值,但不交换它们的引用。例如,arraylist1(1)交换后引用同一类,但其值已更改。

如果我以这种方式更改它们

Dim someclass1 as new someclass
Dim someclass2 as new someclass
arraylist1(1) = someclass1
arraylist1(2) = someclass2
temp = arraylist1(1)
arraylist1(1) = arraylist1(2)
arraylist1(2) = temp

它只交换引用。arraylist1(1)仅引用someclass2,但实际上我希望它引用具有someclass2值的someclass1。 现在,我就一一交换他们的重要特质。

1 个答案:

答案 0 :(得分:2)

您需要自己一个一个地复制属性。您可以通过在类中添加两个方法来使其变得更简单:

Public Class SampleClass
    Public Property Id As Integer
    Public Property Name As String

    Public Function Clone() As SampleClass
        Return New SampleClass With
        {
            .Id = Me.Id,
            .Name = Me.Name
        }
    End Function

    Public Sub Init(input As SampleClass)
        With Me
            .Id = input.Id
            .Name = input.Name
        End With
    End Sub

    Public Shared Sub SwapValues(value1 As SampleClass, value2 As SampleClass)
        Dim temp = value1.Clone()
        value1.Init(value2)
        value2.Init(temp)
    End Sub
End Class

然后尝试交换值时:

SampleClass.SwapValues(list(0), list(1))