Equal can be used to compare the references of two objects.
However, it is more difficult to compare the attributes of two objects. Write a method for reference only:
1 public static bool PropertyEquals (object AObject1, object AObject2)
2 {
3
4 if (object. ReferenceEquals (AObject1, AObject2) return true; // same instance
5 if (object. Equals (AObject1, AObject2) return true; // Same Value
6 if (AObject1 = null | AObject2 = null) return false; // The value is empty.
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 ()! = // Different types
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}
Among them, the judgment of the second and 28 rows requires personalization, and the applicable scenario is to call other classes or lists in the class <>.