理解CSharp 语言中相等Equality 和唯一 Identity

c#有一个“Equals”方法,可以用来比较两个对象。我将试着用例子来解释等式和同一性的概念。

  1. namespace TestEqualityDemo
  2. {
  3. class Program
  4. {
  5. static void Main(string[] args)
  6. {
  7. TestEquality test1 = new TestEquality();
  8. test1.FirstName = "Tom";
  9. test1.FirstName = "Cruise";
  10. TestEquality test2 = new TestEquality();
  11. test2.FirstName = "Tom";
  12. test2.FirstName = "Cruise";
  13. TestEquality test3 = test2;
  14. bool areEqual = test1.Equals(test2);
  15. System.Console.WriteLine("Are test1 and test2 are Equal:" + areEqual);
  16. areEqual = test2.Equals(test3);
  17. System.Console.WriteLine("Are test2 and test3 are Equal:" + areEqual);
  18. System.Console.ReadLine();
  19. }
  20. }
  21. class TestEquality
  22. {
  23. public string FirstName { getset; }
  24. public string LastName { getset; }
  25. }
  26. }

输出:

  1. Are test1 and test2 Equal:False
  2. Are test2 and test3 Equal:True

在上面的例子中

即使test1和test2包含FirstName和LastName的值相同,“Equals”方法也返回False。这是因为Equals方法的默认实现不检查是否相等;它检查Identity(对象引用地址)。这意味着test1和test2必须引用完全相同的对象,然后只有它返回True,否则,它将返回False。

当test2和test3引用相同的对象时,它返回True。根据上面的程序,我们可以得出等号的默认实现,这意味着只有当两个变量指向同一个对象时,它才会返回True。

然后,出现了如何在c#中检查等式的问题,答案是覆盖Equals方法的默认实现。

这里是Equals方法的默认实现。

  1. public virtual bool Equals(Object obj)
  2. {
  3. //If both the references points to the same object then only return true
  4. if (this == obj)
  5. {
  6. return true;
  7. }
  8. return false;
  9. }

必须考虑以下几点来覆盖Equals方法,

如果obj参数为空,则返回false

如果this和obj引用相同的对象,则返回True。这可以在与许多字段进行比较时提高性能

如果this和obj指的是不同的类型,则返回False,因为没有必要比较不同类型的对象;例如,如果我们比较一个字符串对象和DateTime对象,因为它们在任何情况下都不相等。

将该对象的每个字段与obj对象的相应字段进行比较。

最后,调用基类=方法。

以上是重写Equals方法进行比较的最佳步骤。

让我们为TestEquality类实现Equals方法:

  1. namespace TestEqualityDemo
  2. {
  3. class Program
  4. {
  5. static void Main(string[] args)
  6. {
  7. TestEquality test1 = new TestEquality();
  8. test1.FirstName = "Tom";
  9. test1.FirstName = "Cruise";
  10. TestEquality test2 = new TestEquality();
  11. test2.FirstName = "Tom";
  12. test2.FirstName = "Cruise";
  13. TestEquality test4 = new TestEquality();
  14. test2.FirstName = "Will";
  15. test2.FirstName = "Smith";
  16. TestEquality test3 = test2;
  17. bool areEqual = test1.Equals(test2);
  18. System.Console.WriteLine("Are test1 and test2 Equal:" + areEqual);
  19. areEqual = test2.Equals(test3);
  20. System.Console.WriteLine("Are test2 and test3 Equal:" + areEqual);
  21. System.Console.ReadLine();
  22. areEqual = test2.Equals(test4);
  23. System.Console.WriteLine("Are test2 and test4 Equal:" + areEqual);
  24. System.Console.ReadLine();
  25. }
  26. }
  27. class TestEquality
  28. {
  29. public string FirstName { getset; }
  30. public string LastName { getset; }
  31. public override bool Equals(System.Object obj)
  32. {
  33. //If the obj argument is null return false
  34. if (obj == null)
  35. return false;
  36. //If both the references points to the same object then only return true
  37. if (this == obj)
  38. return true;
  39. //If this and obj are referring to different type return false
  40. if (this.GetType() != obj.GetType())
  41. return false;
  42. //Compare each field of this object with respective field of obj object
  43. TestEquality test = (TestEquality)obj;
  44. if (this.FirstName == test.FirstName &&
  45. this.LastName == test.LastName)
  46. {
  47. return true;
  48. }
  49. return false;
  50. }
  51. }
  52. }

输出:

  1. Are test1 and test2 Equal:True
  2. Are test2 and test3 Equal:True
  3. Are test2 and test4 Equal:False

在上面的程序中,

test1和test2的所有字段都相等,所以Equals方法返回true。

test2和test3引用同一个对象,因此它也会返回false。

在test2和test4中,如果FirstName和LastName的值不同,则返回false

重写的Equals方法必须遵循下面的规则:

=必须是自反的,也就是x.Equals(x)必须返回true。

=必须是对称的,即 x.Equals(y)必须返回与 y.Equals(x)相同的值

等号必须是传递i。如果x.Equals(y) 返回true, y.Equals(z) 返回true,那么x.Equals(z)必须返回true。

如果重写的Equals方法不遵循上述规则,那么您的应用程序可能会中断或产生意外结果。

另外,在C#里为什么重载了Equals()就要重载GetHashCode()?发现如果只重载Equals的话,编译器会给一个警告:

warning CS0659: 'UseCom.Program.b' overrides Object.Equals(object o) but does not override Object.GetHashCode()

在解释这个问题之前需要先把Equals()和GetHashCode()方法进行深入了解。

首先先谈一下Equals()这个方法:

Equals()方法,来自于Object,是我们经常需要重写的方法。此方法的默认实现大概是这样的:

public virtual bool Equals(object obj){  if(obj==null) return false;  if(GetType() != obj.GetType()) return false;  return true;}

在很多地方都是特殊处理的,此处就不做深究了。

Ps:按Jeffrey Richter的说法,在值类型使用Equals()时,因为Equals()使用了反射,在比较时会影响效率。

说完Equals()后再来聊一聊GetHashCode()。

其实GetHashCode()在操作值类型的时候也是被System.ValueType()重写的。经过楼主测试的几个常用值类型来看,值类型的GetHashCode()基本都是原值输出(特指整数,Int32除外),真实性有待验证。

结果如下:

理解CSharp 语言中相等Equality 和唯一 Identity

说完值类型,说一下引用类型,先看下面这张运行结果:

理解CSharp 语言中相等Equality 和唯一 Identity

从上图的结果可以看出,虽然string是引用类型,但是只要值一样,返回的HashCode也是一样的,这取决于它的特殊性。而我们自己写的类型Coordinates同样的值但返回的HashCode却不一样,我们可以简单的理解为是coor1与coor2的内存地址不同,所以CLR认为它们是不一样的。

Ps:在程序的生命周期中,相同的对象、变量返回的HashCode是相同的,并且是唯一的。但是绝对不允许做持久性存储,程序一旦结束并重新启动后,同样的对象无法获得上次程序运行时的HashCode。

了解了两个方法后,开始今天的重点话题。

其实在上面的两个对象中(coor1、coor2),coor1.Equals(coor2)的返回结果为false(因为内存地址不同),如果我们想让它们的返回结果为true的话,只能重写Equals方法(如下图)。

理解CSharp 语言中相等Equality 和唯一 Identity

重点来了,重写完Equals以后,vs发出了警告,虽然程序猿从来都是无视警告的,但这个警告确实有必要了解一下,先来看下面这三段代码。

代码段一、二:

理解CSharp 语言中相等Equality 和唯一 Identity

代码段三:

理解CSharp 语言中相等Equality 和唯一 Identity

看完这三段代码,应该就理解为什么要重写Equal时有必要重写GetHashCode了。

当然,如果你没打算在代码中使用Dictionary或HashTable就无所谓写不写了,换句话说,如果要把引用类型做为Dictionary或HashTable的key使用时,必须重写这两个方法。

。其结果就是,存储的时候你可能任性的存,在取值的时候就是你哭着找不着娘了。

好了,说了这么多你应该对这两个方法有了重新的认识了吧。如果还是不明白的话,用代码实现一下,保准明白。

http://www.cnblogs.com/xiaochen-vip8/articles/5506478.html

猜你喜欢

转载自blog.csdn.net/flysnowjava/article/details/80777032
今日推荐