本文主要是介绍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;
这篇关于C# 深拷贝的四种方式的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!