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

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

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


   

        /// 
        /// 复制新增
        /// 
        /// 实体1(传入一个新实例)
        /// 实体2(所复制的实例)
        /// 转换过程中过滤字段列表
        /// 
        public static T1 DifferenceComparisonData(T1 newInstance, T2 copyInstance, List 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 exclude = new List() { "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;

            }

        }

 

你可能感兴趣的:(程序人生,.NET,WPF相关)