Comparison of Two Object Attributes

Source: Internet
Author: User

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 <>.
 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.