C# 对象间的 深拷贝 实现

<?xml version="1.0" encoding="UTF-8"?>
    以下的这个类实现了 2个含有部分字段名字相同 的对象的 赋值拷贝。


public class ShallowCopyHelper
    {
        public static void CopyPropertiesValue( object objFrom, object objTo)
        {
            if ( null == objFrom)
            {
                return ;
            }

            if ( null == objTo)
            {
                return ;
            }

            Type typeFrom = objFrom.GetType();
            Type typeTo = objTo.GetType();

            if (objFrom is IList )
            {
                try
                {
                    int count = (objFrom as IList ).Count;
                    for ( int i = 0; i < count; i++)
                    {
                        CopyPropertiesValue((objFrom as IList )[i], (objTo as IList )[i]);
                    }
                }
                catch
                {
                    //
                }
            }
            else
            {
                foreach (System.Reflection. PropertyInfo pi in
                    typeFrom.GetProperties(System.Reflection. BindingFlags .Public | System.Reflection. BindingFlags .Instance))
                {
                    try
                    {
                        object valueFrom = typeFrom.GetProperty(pi.Name).GetValue(objFrom, null );
                        object valueTo = typeTo.GetProperty(pi.Name).GetValue(objTo, null );

                        if (typeFrom.GetProperty(pi.Name).PropertyType.IsClass
                            && !typeFrom.GetProperty(pi.Name).PropertyType.IsPrimitive
                            && !(valueFrom is String ))
                        {
                            CopyPropertiesValue(valueFrom, valueTo);
                        }
                        else
                        {
                            if (valueFrom == null || !valueFrom.Equals(valueTo))
                            {
                                //Set value to latest data
                                typeTo.GetProperty(pi.Name).SetValue(objTo, valueFrom, null );
                            }
                        }
                    }
                    catch
                    {
                        //
                    }

                }
            }
        }
    }

转载于:https://www.cnblogs.com/muzizongheng/p/3169138.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值