标签:
浅拷贝对引用类型只拷贝地址,拷贝前后共享一块内存区域。深拷贝就是所有的东西全部重新有一份,没有共享存在,推荐使用序列化深拷贝。
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); } } }
标签:
原文地址:http://www.cnblogs.com/zkzk945/p/5133998.html