C# 实体/集合差异比较,比较两个实体或集合值是否一样,将实体2的值动态赋值给实体1(名称一样的属性进行赋值)
标签:i++ int color 比较 summary www. value protect htm
1 ///
2 /// 实体差异比较器
3 ///
4 /// 源版本实体
5 /// 当前版本实体
6 /// true 存在变更 false 未变更
7 protected static bool DifferenceComparison(T1 source, T2 current,Liststring> exclude) where T1 : MBase where T2 : MBase
8 {
9 Type t1 = source.GetType();
10 Type t2 = current.GetType();
11 PropertyInfo[] property1 = t1.GetProperties();
12 //排除主键和基础字段
13 //List exclude = new List() { "Id", "InsertTime", "UpdateTime", "DeleteTime", "Mark", "Version", "Code" };
14 foreach (PropertyInfo p in property1)
15 {
16 string name = p.Name;
17 if (exclude.Contains(name)) { continue; }
18 string value1 = p.GetValue(source, null)?.ToString();
19 string value2 = t2.GetProperty(name)?.GetValue(current, null)?.ToString();
20 if (value1 != value2)
21 {
22 return true;
23 }
24 }
25 return false;
26 }
27 ///
28 /// 集合差异比较器,比较两个实体集合值是否一样
29 ///
30 /// 源版本实体集合
31 /// 当前版本实体集合
32 /// true 存在变更 false 未变更
33 protected static bool DifferenceComparison(List source, List current) where T1 : MBase where T2 : MBase
34 {
35 if (source.Count != current.Count) { return true; }
36 for (int i = 0; i )
37 {
38 bool flag = DifferenceComparison(source[i], current[i]);
39 if (flag) { return flag; }
40 }
41 return false;
42 }
43 ///
44 /// 将实体2的值动态赋值给实体1(名称一样的属性进行赋值)
45 ///
46 /// 实体1
47 /// 实体2
48 /// 赋值后的model1
49 protected static T1 BindModelValue(T1 model1, T2 model2) where T1 : class where T2 : class
50 {
51 Type t1 = model1.GetType();
52 Type t2 = model2.GetType();
53 PropertyInfo[] property2 = t2.GetProperties();
54 //排除主键
55 Liststring> exclude = new Liststring>() { "Id" };
56 foreach (PropertyInfo p in property2)
57 {
58 if (exclude.Contains(p.Name)) { continue; }
59 t1.GetProperty(p.Name)?.SetValue(model1, p.GetValue(model2, null));
60 }
61 return model1;
62 }
List exclude用于排除实体中的字段,这些字段将不参与比较
转自:https://www.cnblogs.com/codelir/p/6856194.html
C# 实体/集合差异比较,比较两个实体或集合值是否一样,将实体2的值动态赋值给实体1(名称一样的属性进行赋值)
标签:i++ int color 比较 summary www. value protect htm
原文地址:https://www.cnblogs.com/shuai7boy/p/8432599.html
评论