Oha*_*der 6 .net c# equality operator-overloading immutability
默认情况下,operator ==通过确定两个引用是否指示相同的对象来测试引用相等性,因此引用类型不需要实现operator ==以获得此功能.当一个类型是不可变的,意味着实例中包含的数据不能被改变时,重载operator ==来比较值的相等而不是引用相等可能是有用的,因为作为不可变对象,只要它们具有它们,它们就可以被认为是相同的相同的价值.不建议在非不可变类型中覆盖operator ==.
任何人都可以解释大胆背后的推理吗?
编辑 - 此外,该指南是否==
仅与运营商相关,还是也适用于该Equals
方法?
Bil*_*eal 16
我的有根据的猜测是让事情像.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
Run Code Online (Sandbox Code Playgroud)
这种行为当然是不一致和混乱的,特别是对新程序员而言 - 但它证明了参考比较和价值比较之间的区别.
如果您遵循此MSDN准则,则遵循重要类(如字符串)所采用的准则.基本上 - 如果比较使用==
成功,程序员就知道该比较将始终成功,只要涉及的引用不会被分配给新对象.程序员不必担心对象的内容不同,因为它们永远不会有所不同:
//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.
Run Code Online (Sandbox Code Playgroud)
归结为指南没有真正的技术原因 - 它只是与框架中的其他类保持一致.
归档时间: |
|
查看次数: |
1506 次 |
最近记录: |