下面小編就為大家帶來一篇C#複製和深度複製的實現方法。小編覺得挺不錯的,現在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
深度複製與淺層複製 (Shallow Copy)的區別在於,淺層複製 (Shallow Copy)只複製實值型別的值,而對於執行個體所包含的對象依然指向原有執行個體。
class Program { [Serializable] public class Car { public string name; public Car(string name) { this.name = name; } } [Serializable] public class Person:ICloneable { public int id; public string name; public Car car; public Person() { } public Person(int id, string name, Car car) { this.id = id; this.name = name; this.car = car; } public Object Clone() //實現ICloneable介面,達到淺層複製 (Shallow Copy)。淺層複製 (Shallow Copy)與深度複製無直接有關係。 對外提供一個建立自身的淺表副本的能力 { return this.MemberwiseClone(); } } //要複製的執行個體必須可序列化,包括執行個體引用的其它執行個體都必須在類定義時加[Serializable]特性。 public static T Copy<T>(T RealObject) { using (Stream objectStream = new MemoryStream()) { //利用 System.Runtime.Serialization序列化與還原序列化完成引用對象的複製 IFormatter formatter = new BinaryFormatter(); formatter.Serialize(objectStream, RealObject); objectStream.Seek(0, SeekOrigin.Begin); return (T)formatter.Deserialize(objectStream); } } static void Main(string[] args) { Person p1 = new Person(1, "Scott", new Car("寶馬")); Console.WriteLine("原始值:P1:id={0}----------->name={1}------>car={2}", p1.id, p1.name, p1.car.name); Person p2 = Copy<Person>(p1); //複製一個對象 Person p3 = p1.Clone() as Person;//淺層複製 (Shallow Copy) Console.WriteLine("改變P1的值"); p1.id = 2; p1.name = "Lacy"; p1.car.name = "紅旗"; Console.WriteLine("P1:id={0}----------->name={1}------>car={2}", p1.id, p1.name, p1.car.name); Console.WriteLine("深度複製:P2:id={0}----------->name={1}------>car={2}", p2.id, p2.name, p2.car.name); Console.WriteLine("淺層複製 (Shallow Copy):P3:id={0}----------->name={1}------>car={2}", p3.id, p3.name, p3.car.name); Console.ReadKey(); }
運行結果:
一、List<T>對象中的T是實值型別的情況(int 類型等)
對於實值型別的List直接用以下方法就可以複製:
List<T> oldList = new List<T>(); oldList.Add(..); List<T> newList = new List<T>(oldList);
二、List<T>對象中的T是參考型別的情況(例如自訂的實體類)
1、對於參考型別的List無法用以上方法進行複製,只會複製List中對象的引用,可以用以下擴充方法複製:
static class Extensions { public static IList<T> Clone<T>(this IList<T> listToClone) where T: ICloneable { return listToClone.Select(item => (T)item.Clone()).ToList(); } //<SPAN style="COLOR: #000000">當然前題是List中的對象要實現ICloneable介面</SPAN> }
2、另一種用序列化的方式對引用對象完成深拷貝,此種方法最可靠
public static T Clone<T>(T RealObject) { using (Stream objectStream = new MemoryStream()) { //利用 System.Runtime.Serialization序列化與還原序列化完成引用對象的複製 IFormatter formatter = new BinaryFormatter(); formatter.Serialize(objectStream, RealObject); objectStream.Seek(0, SeekOrigin.Begin); return (T)formatter.Deserialize(objectStream); } }
3、利用System.Xml.Serialization來實現序列化與還原序列化
public static T Clone<T>(T RealObject) { using(Stream stream=new MemoryStream()) { XmlSerializer serializer = new XmlSerializer(typeof(T)); serializer.Serialize(stream, RealObject); stream.Seek(0, SeekOrigin.Begin); return (T)serializer.Deserialize(stream); }}