两个对象的引用比较可以用Equal
但是两个对象的属性比较就比较麻烦一些,写一个方法,仅供参考:
1 public static bool PropertyEquals(object AObject1, object AObject2)
2 {
3
4 if (object.ReferenceEquals(AObject1, AObject2)) return true; // 相同实例
5 if (object.Equals(AObject1, AObject2)) return true; // 相同值
6 if (AObject1 == null || AObject2 == null) return false; // 其中有空
7
8 PropertyInfo[] vPropertyInfos1 = AObject1.GetType().GetProperties();
9 PropertyInfo[] vPropertyInfos2 = AObject2.GetType().GetProperties();
10
11 if (vPropertyInfos1.Length != vPropertyInfos2.Length) return false;
12
13 for (int i = 0; i < vPropertyInfos1.Length; i++)
14 {
15 if (vPropertyInfos1[i].GetType() != // 类型不相同
16 vPropertyInfos2[i].GetType()) return false;
17
18 object vObject1 = vPropertyInfos1[i].GetValue(AObject1, null);
19 object vObject2 = vPropertyInfos2[i].GetValue(AObject2, null);
20
21 if (vObject1 is Class2 && vObject2 is Class2)
22 {
23 if (PropertyEquals(vObject1, vObject2) == false)
24 {
25 return false;
26 }
27 }
28 else if (vObject1 is List<Class2> && vObject2 is List<Class2>)
29 {
30 if ((vObject1 as List<Class2>).Count != (vObject2 as List<Class2>).Count)
31 {
32 return false;
33 }
34
35 for (int j = 0; j < (vObject1 as List<Class2>).Count; j++)
36 {
37 if (PropertyEquals((vObject1 as List<Class2>)[j], (vObject2 as List<Class2>)[j]) == false)
38 {
39 return false;
40 }
41 }
42 }
43 else
44 {
45 if (!(object.ReferenceEquals(vObject1, vObject2) ||
46 object.Equals(vObject1, vObject2))) return false;
47 }
48
49
50 }
51 return true;
52 }
其中第21行和28行的判断是需要个性化的地方,适用的场合为类中调用其他的类或者List<>。