c# - 在 C# 中为类实现 == 运算符的最佳做法是什么?

标签 c# operators equals-operator

在执行 == 时运营商,我觉得我遗漏了一些要点。
因此,我正在寻找一些最佳实践。
以下是我正在思考的一些相关问题:

  • 如何干净利落地处理引用比较?
  • 是否应该通过 IEquatable<T> 来实现? - 像界面?或覆盖 object.Equals
  • !=呢?接线员?

(此列表可能并不详尽)。

最佳答案

我会关注微软的Guidelines for Overloading Equals() and Operator == .

编辑:Microsoft 的指导方针包含这个重要的评论,这似乎证实了 Henk 的回答:

By default, the operator == tests for reference equality by determining if two references indicate the same object, so reference types do not need to implement operator == in order to gain this functionality. When a type is immutable, meaning the data 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. Overriding operator == in non-immutable types is not recommended

关于c# - 在 C# 中为类实现 == 运算符的最佳做法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1524972/

相关文章:

C# List<Object>.Equals 对象比较失败

java - 不确定如何完成这个 equals 方法

c# - 如何将datagridview中的值存储到集合类C#

c# - 如何在不降低质量的情况下调整图像大小

php 重载等于运算符

c++ - C++ 中的指针否定 (!ptr == NULL)

javascript - 这条线在做什么?到达长度 >>> 0

带有字节数组的 c# 排序列表不起作用

c# - applicationhost.config 中的位置路径未映射到程序集

python - 我们如何/为什么使用 operator.abs