我的猜测是,让事物的操作方式类似于 .NET 中内置类型的操作方式,即在可能的情况下,== 应该像引用相等性一样工作,而 Equals 应该像值相等性一样工作。考虑 ==
和 Equals
之间的实际区别:
object myObj = new Integer(4);
object myObj2 = new Integer(4);
//Note that == is only called if the ref'd objects are cast as a type
//overloading it.
myObj == myObj2; //False (???)
myObj.Equals(myObj2); //True (This call is virtual)
//Set the references equal to each other -- note that the operator==
//comparison now works.
myObj2 = myObj;
myObj == myObj2; //True
myObj.Equals(myObj2); //True
这种行为当然是不一致和令人困惑的,特别是对于新手程序员来说--但它展示了引用比较和值比较之间的区别。
如果您遵循这个MSDN指南,您就可以像字符串(string)类���重要类一样遵循该指南。基本上,如果使用==
进行比较成功,则程序员知道只要涉及到的引用不被分配给新对象,那么该比较将始终成功。程序员永远不必担心对象的内容不同,因为它们永远不会不同:
//Mutable type
var mutable1 = new Mutable(1);
var mutable2 = mutable1;
mutable1 == mutable2; //true
mutable1.MutateToSomethingElse(56);
mutable1 == mutable2; //still true, even after modification
//This is consistent with the framework. (Because the references are the same,
//reference and value equality are the same.) Consider if == were overloaded,
//and there was a difference between reference and value equality:
var mutable1 = new Mutable(1);
var mutable2 = new Mutable(1);
mutable1 == mutable2; //true
mutable1.MutateToSomethingElse(56);
mutable1 == mutable2; //oops -- not true anymore
//This is inconsistent with, say, "string", because it cannot mutate.
这归结于指南没有真正的技术原因 - 它只是为了与框架中的其余类保持一致。
Equals
而不是==
不能解决这个问题。 - Billy ONeal==
和Equals()
。还有getHashCode()
。 - H HSet
使用Equals
而不是==
进行比较,因此关于Set
变得不一致的论点仍然存在。 - Billy ONeal