欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2022-07-08 19:49:58
如何通过值而不是引用交换两个类对象? * 使用语言:VB.NET 原网页:https://*.com/questions/53892521/how-to-exchange-two-class-by-value-not-reference/5389489 ......

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

使用语言:vb.net
原网页:


问题描述

我想交换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