有的时候我们在对一个引用类型的对象进行传递操作的时候希望不要直接修改传递过来的对象,而是复制出一份来操作的时候就可以用下面的类进行复制
using System.IO; using System.Runtime.Serialization; using System.Collections; using System.Collections.Generic; namespace MED.ContactManager.View { public static class ExtensionMethods { public static T DeepCopy<T>(this T oSource,List<System.Type> knowTypes) { T oClone; DataContractSerializer dcs = new DataContractSerializer(typeof(T),knowTypes); using (MemoryStream ms = new MemoryStream()) { dcs.WriteObject(ms, oSource); ms.Position = 0; oClone = (T)dcs.ReadObject(ms); } return oClone; } public static T DeepCopy<T>(this T oSource) { T oClone; DataContractSerializer dcs = new DataContractSerializer(typeof(T)); using (MemoryStream ms = new MemoryStream()) { dcs.WriteObject(ms, oSource); ms.Position = 0; oClone = (T)dcs.ReadObject(ms); } return oClone; } } }