C#对于任意对象进行深拷贝(DeepCopy)

说明:

本文使用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
都能处理。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值