[英]Effective C#: Overriding Object.Equals(), yay or nay?
In the second edition of Effective C# (ISBN-13: 978-0321658708) on page 37, the book reads 在第37页的Effective C#第二版(ISBN-13:978-0321658708)中,该书内容如下
The second function you'll never redefine is static Object.Equals()
你永远不会重新定义的第二个函数是静态Object.Equals()
However, on page 39, the book reads 但是,在第39页,这本书上写着
The point is that if your type should follow value semantics (comparing contents) instead of reference semantics (comparing object identity), you should write your own override of instance Object.Equals()
关键是如果你的类型应该遵循值语义(比较内容)而不是引用语义(比较对象标识),你应该编写自己的实例Object.Equals()覆盖
Would someone be so kind as to explain why one would override 有人会如此善意地解释为什么会覆盖
public virtual bool Equals(object right);
and not 并不是
public static bool Equals(object left, object right);
Thank you :) 谢谢 :)
因为您无法覆盖静态方法。
The first thing to clear is you cannot override static methods. 要清除的第一件事是你不能覆盖静态方法。 The implementation of
实施
public static bool Equals(object left, object right);
cannot be overridden. 不能被覆盖。 The static equals method is only for connivence for not doing a null check.
静态equals方法仅用于不进行空检查。 Internally it first checks for reference equals and then content equals(non static equals method).
在内部,它首先检查引用等于然后内容等于(非静态等于方法)。
In the quotes you mentioned above, the first quote refers the static equals method where as second refers non static equals method both are written in notation as Object.Equals() but notice that the first one says "static Object.Equals()" 在上面提到的引号中,第一个引用引用静态equals方法,其中第二个引用非静态equals方法,两者都以符号形式写为Object.Equals(),但注意第一个引用“static Object.Equals()”
never redefine static Object.Equals()
永远不会重新定义静态 Object.Equals()
You should write your own override of instance Object.Equals()
你应该编写自己的实例 Object.Equals()的覆盖
Notice the difference, static vs instance . 请注意区别, 静态与实例 。 These sentences are not referring to the same method...
这些句子不是指同一种方法......
另外,如果我没有弄错的话,静态的只会比较参考,其中虚拟的那个使你能够编写自己的比较,大多数时候都是基于值而不是参考。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.