说明:
本文使用VS2010,C#
对于任意对象,任意类型进行深拷贝
1. DeepCopyArray
由于Array自身提供的Copy仅仅是浅拷贝,要做到深拷贝,需要对Array中
每一个item进行深拷贝(DeepCopy)。
private static Array DeepCopyArray(Array srcArray)
{
if (srcArray.Length <= 0)
{
return null;
}
// Create new array instance based on source array
Array arrayCopied = Array.CreateInstance(srcArray.GetValue(0).GetType(), srcArray.Length);
// deep copy each object in array
for (int i = 0; i < srcArray.Length; i++)
{
object o = DeepCopy(srcArray.GetValue(i));
arrayCopied.SetValue(o, i);
}
return arrayCopied;
}
2.DeepCopyGenericType
对于List,Dictionary类型,也是对每一个item进行深拷贝(DeepCopy)
private static object DeepCopyGenericType(object srcGeneric)
{
try
{
// Is List
IList srcList = srcGeneric as IList;
if (srcList.Count <= 0)
{
return null;
}
// Create new List<object> instance
IList dstList = Activator.CreateInstance(srcList.GetType()) as IList;
// deep copy each object in List
foreach (object o in srcList)
{
dstList.Add(DeepCopy(o));
}
return dstList;
}
catch(Exception)
{
try
{
IDictionary srcDictionary = srcGeneric as IDictionary;
if (srcDictionary.Count <= 0)
{
return null;
}
// Create new map instance
IDictionary dstDictionary = Activator.CreateInstance(srcDictionary.GetType()) as IDictionary;
// deep copy each object in map
foreach (object o in srcDictionary.Keys)
{
dstDictionary[o] = srcDictionary[o];
}
return dstDictionary;
}
catch (Exception)
{
return null;
}
}
}
3. DeepCopy
入口函数,就一个参数:要深拷贝的对象。
采用递归,代码比较简单,直接上代码:
public static object DeepCopy(object srcobj)
{
if (srcobj == null)
{
return null;
}
Type srcObjType = srcobj.GetType();
// Is simple value type, directly assign
if (srcObjType.IsValueType)
{
return srcobj;
}
// Is array
if (srcObjType.IsArray)
{
return DeepCopyArray(srcobj as Array);
}
// is List or map
else if (srcObjType.IsGenericType)
{
return DeepCopyGenericType(srcobj);
}
// is cloneable
else if (srcobj is ICloneable)
{
// Log informations
return (srcobj as ICloneable).Clone();
}
else
{
// Try to do deep copy, create a new copied instance
object deepCopiedObj = System.Activator.CreateInstance(srcObjType);
// Find out all fields or properties, do deep copy
BindingFlags bflags = BindingFlags.DeclaredOnly | BindingFlags.Public
| BindingFlags.NonPublic | BindingFlags.Instance;
MemberInfo[] memberCollection = srcObjType.GetMembers(bflags);
foreach (MemberInfo member in memberCollection)
{
if (member.MemberType == MemberTypes.Field)
{
FieldInfo field = (FieldInfo)member;
object fieldValue = field.GetValue(srcobj);
field.SetValue(deepCopiedObj, DeepCopy(fieldValue));
}
else if (member.MemberType == MemberTypes.Property)
{
PropertyInfo property = (PropertyInfo)member;
MethodInfo info = property.GetSetMethod(false);
if (info != null)
{
object propertyValue = property.GetValue(srcobj, null);
property.SetValue(deepCopiedObj, DeepCopy(propertyValue), null);
}
}
}
return deepCopiedObj;
}
}
实测,对于各类型Array、List、Dictionary、HashTable、复杂class
都能处理。