C#常用反射法实现相同类,不同类间属性数据拷贝

直接上代码:

        /// <summary>
        /// 相同类的不同实体例间属性拷贝
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="tOne"></param>
        /// <param name="tSecond"></param>
        public static void CopyPropertyDifReflection<T>(T tOne, T tSecond)
        {
            foreach (var itemOut in tSecond.GetType().GetProperties())
            {
                if (itemOut.CanWrite)
                {
                    var itemIn = tOne.GetType().GetProperty(itemOut.Name);
                    if (itemIn != null)
                    {
                        //值不一样时才更新
                        var objIn = itemIn.GetValue(tOne);
                        var objOut = itemOut.GetValue(tSecond);
                        if (objIn == objOut || (objIn == null && objOut != null && string.IsNullOrEmpty(objOut.ToString())) ||
                            (objIn != null && objOut == null && string.IsNullOrEmpty(objIn.ToString()))) continue;
                        if (objIn != null && objIn.Equals(objOut)) continue;

                        itemOut.SetValue(tSecond, objIn);
                    }
                }
            }
        }
        /// <summary>
        /// 不同对象间拷贝相同属性值
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="source"></param>
        /// <param name="target"></param>
        public static void CopyPropertiesTo<T1,T2>(this T1 source, T2 target)
        {
            if (source == null)
                throw new ArgumentNullException(nameof(source));
            if (target == null)
                throw new ArgumentNullException(nameof(target));

            PropertyInfo[] sourceProperties = source.GetType().GetProperties();

            foreach (PropertyInfo sourceProperty in sourceProperties)
            {
                PropertyInfo targetProperty = target.GetType().GetProperty(sourceProperty.Name);
                if (targetProperty != null && targetProperty.CanWrite)
                {
                    targetProperty.SetValue(target, sourceProperty.GetValue(source, null), null);
                }
            }
        }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值