詳解c# 深克隆與淺克隆
前言
我們都知道m(xù)emberwiseclone 會(huì)將淺克隆。
什么是淺克???如何深克隆呢?
正文
public class good{ private good(){ oneclass=new class{ int id=8; string name='id'; } } private static good __good; private static good __good=new good(); public good createinstance() { return __good.memberwiseclone(); } public int a=0; public string b="ab"; pulic class oneclass; }
測(cè)試:
void main() { var student1=good.createinstance(); var student2=good.createinstance(); student1.oneclass.id=9; console.log('student2 oneclass.id{0}',student2.oneclass.id); }
這里我們得出了結(jié)果為9;
ok,那么這真的是個(gè)匪夷所思的問(wèn)題,明明兩個(gè)對(duì)象啊。
那么回歸到淺克隆上。
當(dāng)克隆good的時(shí)候是這樣的。
讓good的classone的引用給了新的克隆對(duì)象。
那么如何深克隆呢?
深克隆其實(shí)就是將對(duì)象序列化,也就是說(shuō)要深克隆的話必須對(duì)象系列化;
public class SerializeHelper { public static string Serializable(object target) { using (MemoryStream steam=new MemoryStream()) { new BinaryFormatter().Serialize(steam,target); return Convert.ToBase64String(steam.ToArray()); } } public static T Derializable<T>(string target) { byte[] targetArray = Convert.FromBase64String(target); using (MemoryStream steam =new MemoryStream(targetArray)) { return (T)(new BinaryFormatter().Deserialize(steam)); } } public static T DeepClone<T>(T t) { return Derializable<T>(Serializable(t)); } }
改變一個(gè)good 類。
public class good{ private good(){ oneclass=new class{ int id=8; string name='id'; } } private static good __good; private static good __good=new good(); public good createinstance() { return SerializeHelper.DeepClone(__good.memberwiseclone()); } public int a=0; public string b="ab"; pulic class oneclass; }
測(cè)試一下:
void main() { var student1=good.createinstance(); var student2=good.createinstance(); student1.oneclass.id=9; console.log('student2 oneclass.id{0}',student2.oneclass.id); }
以上就是詳解c# 深克隆與淺克隆的詳細(xì)內(nèi)容,更多關(guān)于c# 深克隆與淺克隆的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
C#中方法的直接調(diào)用、反射調(diào)用與Lambda表達(dá)式調(diào)用對(duì)比
這篇文章主要介紹了C#中方法的直接調(diào)用、反射調(diào)用與Lambda表達(dá)式調(diào)用對(duì)比,本文著重講解了方法的三種調(diào)用方法以及它們的性能對(duì)比,需要的朋友可以參考下2015-06-06對(duì)指定的網(wǎng)頁(yè)進(jìn)行截圖的效果 C#版
對(duì)指定的網(wǎng)頁(yè)進(jìn)行截圖的效果 C#版...2007-08-08C#實(shí)現(xiàn)ComboBox變色的示例代碼
這篇文章主要為大家詳細(xì)介紹了C#如何實(shí)現(xiàn)ComboBox變色的效果,文中的示例代碼講解詳細(xì),對(duì)我們學(xué)習(xí)C#有一定的幫助,感興趣的小伙伴可以跟隨小編一起了解一下2023-01-01C#實(shí)現(xiàn)二維數(shù)據(jù)數(shù)組導(dǎo)出到Excel的詳細(xì)過(guò)程
將數(shù)據(jù)庫(kù)查詢出來(lái)的數(shù)據(jù)導(dǎo)出并生成?Excel?文件,是項(xiàng)目中經(jīng)常使用的一項(xiàng)功能,本文將介紹通過(guò)數(shù)據(jù)集生成二維數(shù)據(jù)數(shù)組并導(dǎo)出到?Excel,文中有詳細(xì)的代碼供大家參考,需要的朋友可以參考下2024-09-09