“==”和equal的比较

 1 class People
 2     {
 3         public string A { get; set; }
 4         public string B { get; set; }
 5         public string C { get; set; }
 6 
 7        
 8         public override bool Equals(object obj)
 9         {
10 
11             if (obj == null)
12                 return false;
13             if (ReferenceEquals(obj, this))
14                 return true;
15             People p = obj as People;
16             if (p == null)
17                 return false;
18             if (p.A.Equals(this.A) && p.B.Equals(this.B) && p.C.Equals(this.C))
19                 return true;
20             return false;
21         }
22         /// <summary>
23         /// 忽略空格和null,进行比较。
24         /// </summary>
25         /// <param name="str1"></param>
26         /// <param name="str2"></param>
27         /// <returns></returns>
28         private bool CompareTwo(string str1, string str2)
29         {
30             if (string.IsNullOrEmpty(str1))
31                 str1 = "";
32             if (string.IsNullOrEmpty(str2))
33                 str2 = "";
34             return str1.Trim().Equals(str2.Trim());
35 
36         }
37 
38 
39     }
View Code

判断类的两个实例的值是否相等,需要重写Equal方法。

在值类型中:

“==”和equal相同,只比较“值的内容”是否相等。

在引用类型中:

“==”:比较的是类的引用地址。此处string比较特殊,比较的是值,因为C#内部重写了该方法,用的是equal。

“equal”:始终比较的是“值的内容

猜你喜欢

转载自www.cnblogs.com/wwz-wwz/p/10019548.html