最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

C#中Clone一個(gè)對(duì)象的值到另一個(gè)對(duì)象案例

 更新時(shí)間:2020年12月09日 09:55:07   作者:這名字不好聽  
這篇文章主要介紹了C#中Clone一個(gè)對(duì)象的值到另一個(gè)對(duì)象案例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧

我也只是略懂皮毛,自己記錄下方便以后看的,各位有任何高見煩請(qǐng)留言,謝謝,抱拳!

想只復(fù)制值需要你的類實(shí)現(xiàn)ICloneable接口,并實(shí)現(xiàn)public object Clone()方法,其中

{
return this as object; //引用同一個(gè)對(duì)象
return this.MemberwiseClone(); //淺復(fù)制
return new DrawBase() as object;//深復(fù)制
}

引用

即相當(dāng)于用等號(hào)(=)賦值,相當(dāng)于 this,引用,兩者共用一套數(shù)據(jù)

深復(fù)制

新建對(duì)象,需手動(dòng)賦值,所有數(shù)據(jù)新建,兩個(gè)對(duì)象完全無關(guān)

淺復(fù)制

只復(fù)制值而不要引用,但只作用于基礎(chǔ)類型(int,float,string也好使),對(duì)于引用類型(如自建類)不生效。如果只想要值,可在自建類里也是用這種辦法,如a.t = T.Clone() as T; 最后將a返回,即可解決這個(gè)問題。

本次主談淺復(fù)制,如有形如:

 class a : ICloneable
{
 public int i;
 public string str;
 public b ins;
 
 public object Clone()
 {
 return this.MemberwiseClone(); //淺復(fù)制
 }
}
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);
} 

首先這段代碼實(shí)際上是不會(huì)運(yùn)行的,因?yàn)闇\復(fù)制不會(huì)復(fù)制引用,也就是在print(t2.ins.bi)時(shí),實(shí)際上t2.ins是空,但t2.i和t2.str是有值的,而且在后續(xù)對(duì)t2.i和t2.str進(jìn)行改動(dòng)時(shí)并不會(huì)影響到t1的值,這一部分的結(jié)果使我們想要的。

但實(shí)際上類里有屬性是引用是難以避免甚至是很常見的,這種情況我們只需要在類b中也實(shí)現(xiàn)ICloneable接口并實(shí)現(xiàn)

public object Clone()
{
 return this.MemberwiseClone(); //淺復(fù)制
}

同時(shí)修改類a中的Clone方法為:

public object Clone()
{
 a T = this.MemberwiseClone() as a; //淺復(fù)制
 T.ins = ins.Clone() as b;
 return T;
}

由此,t2將獲取到t1的所有值,且對(duì)t2修改時(shí),并不會(huì)影響到t1。

補(bǔ)充知識(shí):C++中實(shí)現(xiàn)對(duì)象的clone()

在C#中,許多對(duì)象自動(dòng)實(shí)現(xiàn)了clone函數(shù),在C++中,要拷貝一個(gè)對(duì)象,除了自定義一個(gè)拷貝構(gòu)造函數(shù)來實(shí)現(xiàn)對(duì)象復(fù)制外,還可以像C#中那樣實(shí)現(xiàn)一個(gè)clone函數(shù),這需要借助編譯器實(shí)現(xiàn)的一個(gè)隱藏拷貝構(gòu)造函數(shù),這樣的做法,更省心。

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

class CA
{
public:
 int value;
 CA* clone() const { return new CA( *this );}
 //僅一個(gè)構(gòu)造函數(shù)
 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;
}

以上這篇C#中Clone一個(gè)對(duì)象的值到另一個(gè)對(duì)象案例就是小編分享給大家的全部內(nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。

相關(guān)文章

最新評(píng)論

江北区| 隆尧县| 正蓝旗| 新密市| 柳河县| 新乡县| 于都县| 太原市| 南开区| 温州市| 郓城县| 远安县| 新邵县| 东乡族自治县| 梁平县| 绿春县| 金沙县| 富顺县| 洛宁县| 什邡市| 康马县| 南丰县| 子长县| 济阳县| 汉源县| 泊头市| 绥阳县| 青铜峡市| 淳化县| 汤原县| 武邑县| 大石桥市| 乌拉特前旗| 西林县| 石阡县| 永福县| 兰考县| 惠东县| 成都市| 丰镇市| 新乡县|