.net - 覆盖 Equals 方法时是否需要覆盖 == 和 != 运算符? (。网)

标签 .net operators overriding equals-operator

或者建议这样做?
为什么?

最佳答案

guidelines for overriding Equals() and operator== .

引用:

By default, the operator == tests for reference equality by determining whether two references indicate the same object. Therefore, reference types do not have to implement operator == in order to gain this functionality. When a type is immutable, that is, the data that is contained in the instance cannot be changed, overloading operator == to compare value equality instead of reference equality can be useful because, as immutable objects, they can be considered the same as long as they have the same value. It is not a good idea to override operator == in non-immutable types.



基本上:

如果你想让 == 和 != 表现得像 Equals(..)!Equals(..)你需要实现运营商。您通常只对不可变类型执行此操作。

关于.net - 覆盖 Equals 方法时是否需要覆盖 == 和 != 运算符? (。网),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1222035/

相关文章:

c# - 解析来自服务器的 UTF8 JSON 响应

linux - 逻辑与操作的困惑

c++ - 通过引用传递 - 运算符重载

c - 为什么模数 (%) 运算符适用于 char 但不适用于浮点类型?

c# - 重写属性上的 .net XmlSerializer

java - 使用覆盖方法

c# - 如何计算 WPF 中的非客户端窗口大小?

c# - 什么是System.Void?

java - 重写 - 降低方法作为私有(private)方法的可见性, eclipse 错误

c# - 如何将 .net 下拉列表绑定(bind)到 CRM 2011 选项集