在执行 ==
时运营商,我觉得我遗漏了一些要点。
因此,我正在寻找一些最佳实践。
以下是我正在思考的一些相关问题:
- 如何干净利落地处理引用比较?
- 是否应该通过
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/