C#中的深复制与浅复制
??? C#中分為值類型和引用類型,值類型的變量直接包含其數據,而引用類型的變量則存儲對象的引用。
??? 對于值類型,每個變量都有自己的數據副本,對一個變量的操作不可能影響到另一個變量。如
class Program{static void Main(string[] args){int a = 3;int b=a;a = 5;Console.WriteLine("a={0},b={1}",a,b);Console.ReadKey();}}?
??? 輸出為:
??? a=5,b=3
??? 而對于引用類型,兩個變量可能引用同一個對象,因此對一個變量的操作可能影響到另一個變量所引用的對象。
public class A { public int param; public A(int i) { this.param = i; } }A a1 = new A(5); A a2 = a1; a1.param = 10; Console.WriteLine("a1.param={0},a2.param={1}",a1.param,a2.param); Console.ReadKey();??? 輸出為:
??? a1.param=10,a2.param=10
??? 可見改變了a1中的param值,也會同樣改變a2中的param值,因為它們指向的是同一個實例,其實就是同一個。
??? 淺復制:實現淺復制需要使用Object類的MemberwiseClone方法創建一個淺表副本。
??? 深復制:需實現ICloneable接口中的Clone方法,重新實例化一個對象作為返回值。
??? 對于復制對象中的值類型,結果正確:
public class Person :ICloneable{private int age;public int Age{get{return age;}set{this.age = value;}}public Person(int i){this.age = i;}public object Clone(){//return this.MemberwiseClone();return new Person(this.age) as object;}}Person p1 = new Person(5);Person p2 = (Person)p1.Clone();p1.Age = 10;Console.WriteLine("p1.age={0},p2.age={1}",p1.Age,p2.Age);Console.ReadKey();??? 利用 return this.MemberwiseClone()和return new Person(this.age) as object輸出的值均為:
??? p1.age=10,p2.age=5
??? 但是若是復制對象中的引用類型時,淺復制就會出現問題,如下:
public class Education{public int score;}public class Person:ICloneable{public Education education=new Education ();public Person(int i){education.score = i;}public object Clone(){return this.MemberwiseClone();//return new Person(this.education.score) as object; }}Person p1 = new Person(59);Person p2 = (Person)p1.Clone();p1.education.score = 99;Console.WriteLine("p1.education.score={0},p2.education.score={1}", p1.education.score, p2.education.score);Console.ReadKey();
??? 當用return this.MemberwiseClone()時,即用淺復制時,輸出為:
??? p1.education.score=99,p2.education.score=99
??? 這與原來的代碼意圖不符,當用return new Person(this.education.score) as object時,輸出為
??? p1.education.score=99,p2.education.score=59
???
轉載于:https://www.cnblogs.com/Celvin-Xu/p/3206568.html
總結
以上是生活随笔為你收集整理的C#中的深复制与浅复制的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 简单快速安装Apache+PHP+MyS
- 下一篇: C#实现数据回滚,A事件和B事件同时执行