C#对集合进行深度复制,C#深度复制封装

    技术2022-07-16  82

    C#对集合进行深度复制,C#深度复制封装

    场景说明

    场景说明

    有时候方法更改外部传进来的对象,又不得不对其进行修改再返回结果时 直接上代码

    pubilc class ToolX { public static object Clone(object obj) { if (obj == null || obj.GetType().BaseType == typeof(ValueType)) return obj; try { Type t = obj.GetType(); if (obj is ICloneable) return (obj as ICloneable).Clone(); if (t == typeof(System.Data.DataTable)) return (obj as System.Data.DataTable).Copy(); if (t == typeof(System.Data.DataSet)) return (obj as System.Data.DataSet).Copy(); if (obj is System.Collections.IDictionary) { var dic = (obj as System.Collections.IDictionary); var nDic = t.Assembly.CreateInstance(t.FullName) as System.Collections.IDictionary; if (dic != null && nDic != null) { foreach (var k in dic.Keys) { if (nDic.Contains(k) == false) nDic.Add(k, dic[k]); } return nDic; } } if (t.IsGenericType)//是集合 { //A方案,不需要对类标记Serializable,但性能比B方案差(千次170ms) object retval; using (System.IO.MemoryStream ms = new System.IO.MemoryStream()) { System.Xml.Serialization.XmlSerializer xml = new System.Xml.Serialization.XmlSerializer(t); xml.Serialize(ms, obj); ms.Seek(0, System.IO.SeekOrigin.Begin); retval = xml.Deserialize(ms); ms.Close(); } return retval; //B方案,需要对类标记Serializable(千次40ms) //using (System.IO.Stream objectStream = new System.IO.MemoryStream()) //{ // System.Runtime.Serialization.IFormatter formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter(); // formatter.Serialize(objectStream, obj); // objectStream.Seek(0, System.IO.SeekOrigin.Begin); // return formatter.Deserialize(objectStream); //} } else //是一个类 { var nObj = t.Assembly.CreateInstance(t.FullName); foreach (System.Reflection.FieldInfo f in t.GetFields()) f.SetValue(nObj, f.GetValue(obj)); foreach (System.Reflection.PropertyInfo p in t.GetProperties()) p.SetValue(nObj, p.GetValue(obj, null), null); return nObj; } } catch (Exception e) { /*日志自行实现*/ throw e; } return obj; } }

    原文链接:http://blog.albsz.cn/2020-07-03-csharp-clone.html

    Processed: 0.012, SQL: 9