@TOC
场景说明
有时候方法更改外部传进来的对象,又不得不对其进行修改再返回结果时
直接上代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
| 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) { 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; } 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; } }
|
原文链接:/2020-07-03-csharp-clone.html
打赏