標籤:
淺拷貝對參考型別只拷貝地址,拷貝前後共用一塊記憶體地區。深拷貝就是所有的東西全部重新有一份,沒有共用存在,推薦使用序列化深拷貝。
using System;using System.IO;using System.Runtime.Serialization.Formatters.Binary;namespace ConsoleApplication1{ internal class Program { [Serializable] public class TV { public TV() { } public TV(int max) { MaxChannel = max; } private int maxChannel; public override string ToString() { return string.Format("MaxChannel: {0}", MaxChannel); } public int MaxChannel { get { return maxChannel; } set { maxChannel = value; } } } [Serializable] public struct Light { public string name; public Light(string name) { this.name = name; } public override string ToString() { return string.Format("Name: {0}", name); } } [Serializable] public class House : ICloneable { public TV tv; public Light light; public House(TV tv, Light light) { this.tv = tv; this.light = light; } public override string ToString() { return string.Format("Light: {0}, Tv: {1}", light, tv); } public object Clone() { //淺拷貝 //return MemberwiseClone(); //深拷貝 1 //TV tv = new TV(); //tv.MaxChannel = this.tv.MaxChannel; //Light light = this.light; //House house = new House(tv, light); //return house; //深拷貝2 需要添加[Serializable] using (Stream stream = new MemoryStream()) { BinaryFormatter bf = new BinaryFormatter(); bf.Serialize(stream, this); stream.Seek(0, SeekOrigin.Begin); return bf.Deserialize(stream); } } } private static void Main(string[] args) { TV tv = new TV(10); Light light = new Light("zk"); House house = new House(tv, light); House house1 = (House)house.Clone(); Console.WriteLine(house); Console.WriteLine(house1); house.light.name = "te"; house.tv.MaxChannel = 90; Console.WriteLine(house); Console.WriteLine(house1); } }}
c# 深拷貝 淺拷貝