WPF C# 利用反射进行复制新增

8 篇文章 0 订阅
7 篇文章 0 订阅

   c#利用反射比较两个实体的差异,并把选中行的实例赋值给新的实例(要添加的实例)我所说的实例你可以当做是行

   适用于与复制新增,或者复杂的复制新增主表和子表数据


   

        /// <summary>
        /// 复制新增
        /// </summary>
        /// <typeparam name="T1">实体1(传入一个新实例)</typeparam>
        /// <typeparam name="T2">实体2(所复制的实例)</typeparam>
        /// <param name="exclude">转换过程中过滤字段列表</param>
        /// <returns></returns>
        public static T1 DifferenceComparisonData<T1, T2>(T1 newInstance, T2 copyInstance, List<string> exclude) where T1 : class where T2 : class
        {
            if (true)
            {
                Type newType = newInstance.GetType();
                Type currentType = copyInstance.GetType();
                BindingFlags flags2 = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly | BindingFlags.Instance;
                PropertyInfo[] property1 = newType.GetProperties(flags2);
                //排除主键和基础字段
                //List<string> exclude = new List<string>() { "Id", "InsertTime", "UpdateTime", "DeleteTime", "Mark", "Version", "Code" };
                foreach (PropertyInfo p in property1)
                {
                    string name = p.Name;
                    if (exclude.Contains(name)) { continue; }
                    string newValue = p.GetValue(newInstance, null)?.ToString();
                    string currentValue = currentType.GetProperty(name)?.GetValue(copyInstance, null)?.ToString();
                    if (newValue != currentValue)
                    {
                        #region 
                        //t1.GetField(p.Name).SetValue(t1.GetField(p.Name), value2);
                        //t1.GetField(p.Name).SetValue(t1,value2);   
                        //value1 = t1.se;
                        //p.GetValue(source, null);  
                        #endregion

                        newType.GetProperty(p.Name)?.SetValue(newInstance, p.GetValue(copyInstance, null), null);
                    }
                }
                return newInstance;

            }

        }

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值