C# 根据部分属性来判断俩个对象是否相同

根据部分属性来判断俩个对象是否相同 

代码是第一版本 可能不牢固 有问题请反馈一下 3QU

效果图:

 1     public static class CustomExpand
 2     {
 3         public static bool CustomEquals<T>(this T t, T t1, params Expression<Func<T, object>>[] ex) where T : class
 4         {
 5             List<string> memberList = new List<string>();
 6             foreach (var item in ex)
 7             {
 8                 string memberName = (GetMemberExpression(item.Body)?.Member.Name);
 9                 if (!string.IsNullOrEmpty(memberName))
10                 {
11                     memberList.Add(memberName);
12                 }
13             }
14             Type type = t.GetType();
15             while (memberList.Count > 0)
16             {
17                 PropertyInfo propertyInfo = type.GetProperty(memberList[0]);
18                 switch (propertyInfo.PropertyType.BaseType.FullName)
19                 {
20                     case "System.ValueType":
21                         if (propertyInfo.GetValue(t, null)?.ToString() != propertyInfo.GetValue(t1, null)?.ToString())
22                         {
23                             return false;
24                         }
25                         break;
26                     case "System.Object":
27                         if (SerializerHelper.ToJson(propertyInfo.GetValue(t, null)) != SerializerHelper.ToJson(propertyInfo.GetValue(t1, null)))
28                         {
29                             return false;
30                         }
31                         break;
32                     default:
33                         throw new Exception($"类型:{propertyInfo.PropertyType.BaseType.FullName} 未作处理");
34                         break;
35                 }
36                 memberList.RemoveAt(0);
37             }
38             return true;
39         }
40         public static MemberExpression GetMemberExpression(Expression expression)
41         {
42             if (expression is MemberExpression)
43             {
44                 return expression as MemberExpression;
45             }
46             if (expression is UnaryExpression)
47             {
48                 return GetMemberExpression(((UnaryExpression)expression).Operand);
49             }
50             return null;
51         }
52     }

猜你喜欢

转载自www.cnblogs.com/qhbm/p/9371909.html