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

@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)//是集合
{
//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;
}
}

原文链接:/2020-07-03-csharp-clone.html

打赏
  • 版权声明: 本博客所有文章除特别声明外,著作权归作者所有。转载请注明出处!

撸代码不易,给点物质上的支持吧~

支付宝
微信