软件编程
位置:首页>> 软件编程>> C#编程>> C#中Clone一个对象的值到另一个对象案例

C#中Clone一个对象的值到另一个对象案例

作者:这名字不好听  发布时间:2022-10-11 21:41:14 

标签:C#,Clone,对象

我也只是略懂皮毛,自己记录下方便以后看的,各位有任何高见烦请留言,谢谢,抱拳!

想只复制值需要你的类实现ICloneable接口,并实现public object Clone()方法,其中


{
return this as object; //引用同一个对象
return this.MemberwiseClone(); //浅复制
return new DrawBase() as object;//深复制
}

引用

即相当于用等号(=)赋值,相当于 this,引用,两者共用一套数据

深复制

新建对象,需手动赋值,所有数据新建,两个对象完全无关

浅复制

只复制值而不要引用,但只作用于基础类型(int,float,string也好使),对于引用类型(如自建类)不生效。如果只想要值,可在自建类里也是用这种办法,如a.t = T.Clone() as T; 最后将a返回,即可解决这个问题。

本次主谈浅复制,如有形如:


class a : ICloneable
{
public int i;
public string str;
public b ins;

public object Clone()
{
return this.MemberwiseClone(); //浅复制
}
}
class b
{
public int bi;
}
--------------Program--------------
Main :
{
a t1 = new a();
t1.i = 1;
t1.str = "str1";
t1.ins = new t1();
t1.ins.bi = 111;

a t2 = t1.Clone() as a;
print(t1.i + " " + t2.i);
print(t1.str + " " + t2.str );
print(t1.ins.bi + " " + t2.ins.bi);

t2.i = 2;
t2.str = "str2";
t2.ins.bi = 222;
print(t1.i + " " + t2.i);
print(t1.str + " " + t2.str );
print(t1.ins.bi + " " + t2.ins.bi);
}

首先这段代码实际上是不会运行的,因为浅复制不会复制引用,也就是在print(t2.ins.bi)时,实际上t2.ins是空,但t2.i和t2.str是有值的,而且在后续对t2.i和t2.str进行改动时并不会影响到t1的值,这一部分的结果使我们想要的。

但实际上类里有属性是引用是难以避免甚至是很常见的,这种情况我们只需要在类b中也实现ICloneable接口并实现


public object Clone()
{
return this.MemberwiseClone(); //浅复制
}

同时修改类a中的Clone方法为:


public object Clone()
{
a T = this.MemberwiseClone() as a; //浅复制
T.ins = ins.Clone() as b;
return T;
}

由此,t2将获取到t1的所有值,且对t2修改时,并不会影响到t1。

补充知识:C++中实现对象的clone()

在C#中,许多对象自动实现了clone函数,在C++中,要拷贝一个对象,除了自定义一个拷贝构造函数来实现对象复制外,还可以像C#中那样实现一个clone函数,这需要借助编译器实现的一个隐藏拷贝构造函数,这样的做法,更省心。


#include "stdafx.h"
#include <iostream>

class CA
{
public:
int value;
CA* clone() const { return new CA( *this );}
//仅一个构造函数
CA(int a ){value=a;}
};

int _tmain(int argc, _TCHAR* argv[])
{
CA* objA=new CA(10);
CA* objtemp=objA->clone();
delete objA;
std::cout<<objtemp->value;
delete objtemp;
return 0;
}

来源:https://blog.csdn.net/weixin_41957078/article/details/84667681

0
投稿

猜你喜欢

手机版 软件编程 asp之家 www.aspxhome.com