C#中4種深拷貝辦法引見。本站提示廣大學習愛好者:(C#中4種深拷貝辦法引見)文章只能為提供參考,不一定能成為您想要的結果。以下是C#中4種深拷貝辦法引見正文
1:應用反射完成
public static T DeepCopy<T>(T obj) { //假如是字符串或值類型則直接前往 if (obj is string || obj.GetType().IsValueType) return obj; object retval = Activator.CreateInstance(obj.GetType()); FieldInfo[] fields = obj.GetType().GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static); foreach (FieldInfo field in fields) { try { field.SetValue(retval, DeepCopy(field.GetValue(obj))); } catch { } } return (T)retval; }
2:應用xml序列化和反序列化完成
public T DeepCopy<T>(T obj) { object retval; using (MemoryStream ms = new MemoryStream()) { XmlSerializer xml = new XmlSerializer(typeof(T)); xml.Serialize(ms, obj); ms.Seek(0, SeekOrigin.Begin); retval = xml.Deserialize(ms); ms.Close(); } return (T)retval; }
3:應用二進制序列化和反序列化完成
public static T DeepCopy<T>(T obj) { object retval; using (MemoryStream ms = new MemoryStream()) { BinaryFormatter bf = new BinaryFormatter(); //序列化成流 bf.Serialize(ms, obj); ms.Seek(0, SeekOrigin.Begin); //反序列化成對象 retval = bf.Deserialize(ms); ms.Close(); } return (T)retval; }
4:應用silverlight DataContractSerializer完成,用於在silverlight 客戶端應用
public static T DeepCopy<T>(T obj) { object retval; using (MemoryStream ms = new MemoryStream()) { DataContractSerializer ser = new DataContractSerializer(typeof(T)); ser.WriteObject(ms, obj); ms.Seek(0, SeekOrigin.Begin); retval = ser.ReadObject(ms); ms.Close(); } return (T)retval;
彌補:第一個曾經經由過程遞歸完成了深拷貝。