C# 深拷贝的四种方式
作者:互联网
1:利用反射实现
1 public static T DeepCopy(T obj) 2 { 3 //如果是字符串或值类型则直接返回 4 if (obj is string || obj.GetType().IsValueType) return obj; 5 6 object retval = Activator.CreateInstance(obj.GetType()); 7 FieldInfo[] fields = obj.GetType().GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static); 8 foreach (FieldInfo field in fields) 9 { 10 try { field.SetValue(retval, DeepCopy(field.GetValue(obj))); } 11 catch { } 12 } 13 return (T)retval; 14 }
2:利用xml序列化和反序列化实现
1 public T DeepCopy(T obj) 2 { 3 object retval; 4 using (MemoryStream ms = new MemoryStream()) 5 { 6 XmlSerializer xml = new XmlSerializer(typeof(T)); 7 xml.Serialize(ms, obj); 8 ms.Seek(0, SeekOrigin.Begin); 9 retval = xml.Deserialize(ms); 10 ms.Close(); 11 } 12 return (T)retval; 13 }
3:利用二进制序列化和反序列化实现
1 public static T DeepCopy(T obj) 2 { 3 object retval; 4 using (MemoryStream ms = new MemoryStream()) 5 { 6 BinaryFormatter bf = new BinaryFormatter(); 7 //序列化成流 8 bf.Serialize(ms, obj); 9 ms.Seek(0, SeekOrigin.Begin); 10 //反序列化成对象 11 retval = bf.Deserialize(ms); 12 ms.Close(); 13 } 14 return (T)retval; 15 }
4:利用silverlight DataContractSerializer实现,用于在silverlight 客户端使用
1 public static T DeepCopy(T obj) 2 { 3 object retval; 4 using (MemoryStream ms = new MemoryStream()) 5 { 6 DataContractSerializer ser = new DataContractSerializer(typeof(T)); 7 ser.WriteObject(ms, obj); 8 ms.Seek(0, SeekOrigin.Begin); 9 retval = ser.ReadObject(ms); 10 ms.Close(); 11 } 12 return (T)retval;
标签:obj,MemoryStream,C#,ms,DeepCopy,new,拷贝,retval,四种 来源: https://www.cnblogs.com/devgis/p/16418594.html