using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.Serialization.Formatters.Binary; using System.Text; namespace ConsoleApplication1 { public class Program { public static void Main(string[] args) { ItemList listBefore = (ItemList)new List<Item>(); listBefore.Add(new Item() { ID = 12, Name = "张三" }); listBefore.Add(new Item() { ID = 18, Name = "李四" }); ItemList listAfter = new ItemList(); listAfter = (ItemList)listBefore.Clone(); Console.WriteLine("Before 未修改" + listBefore[0].ID); Console.WriteLine("Before 未修改" + listBefore[0].Name); Console.WriteLine(); Console.WriteLine(); Console.WriteLine("After 未修改" + listAfter[0].ID); Console.WriteLine("After 未修改" + listAfter[0].Name); Console.WriteLine(); Console.WriteLine(); listAfter[0].ID = 110; listAfter[0].Name = "小孩"; Console.WriteLine("Before 以修改" + listBefore[0].ID); Console.WriteLine("Before 以修改" + listBefore[0].Name); Console.WriteLine(); Console.WriteLine(); Console.WriteLine("After 以修改" + listAfter[0].ID); Console.WriteLine("After 以修改" + listAfter[0].Name); Console.WriteLine(); Console.WriteLine(); } } [Serializable] public class Item { public int ID { get; set; } public string Name { get; set; } } [Serializable] public class ItemList : List<Item>, ICloneable { public object Clone() { MemoryStream ms = new MemoryStream(); object obj; try { BinaryFormatter bf = new BinaryFormatter(); bf.Serialize(ms, this); ms.Seek(0, SeekOrigin.Begin); obj = bf.Deserialize(ms); } finally { ms.Close(); } return obj; } } }
时间: 2024-12-31 03:30:28