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

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

使用语言:VB.NET
原网页:https://stackoverflow.com/questions/53892521/how-to-exchange-two-class-by-value-not-reference/53894896#53894896


问题描述

我想交换List中有两个引用类型对象的,而不是引用。比如,List1(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对象,但是我想要的效果是它依然引用someclass1同时拥有someclass2的值。


解答

你需要自己一个个复制属性。你可以在你的类里添加两个方法让这更简单一些。

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
posted @ 2019-01-08 18:54 shadowfish0 阅读(...) 评论(...) 编辑 收藏