- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
我明白了为我的对象显式实现 Equals 和 GetHashCode 的意义。
但我想知道像这样显式实现 == 和 != 运算符是否有意义:
public static bool operator ==(Salutation left, Salutation right)
{
return Equals(left, right);
}
调用 == 时,C# 不会自动使用 Equals 方法吗?
最佳答案
与 Equals
一起覆盖相等运算符确实有意义。事实上,这是非常可取的。
微软官方已发布Guidelines for Implementing Equals and the Equality Operator (==)在 MSDN 上。我肯定会按照那里推荐的做法去做。主要有两点:
- Implement the GetHashCode method whenever you implement the Equals method. This keeps Equals and GetHashCode synchronized.
- Override the Equals method whenever you implement the equality operator (==), and make them do the same thing. This allows infrastructure code such as Hashtable and ArrayList, which use the Equals method, to behave the same way as user code written using the equality operator.
Jon Skeet 还写了一篇 useful MSDN blog post关于这个主题,总结了 Equals
和 ==
运算符在默认情况下如何在引用/值类型上工作。
下面引用了最重要的部分:
The Equals method is just a virtual one defined in System.Object, and overridden by whichever classes choose to do so. The == operator is an operator which can be overloaded by classes, but which usually has identity behaviour.
For reference types where == has not been overloaded, it compares whether two references refer to the same object - which is exactly what the implementation of Equals does in System.Object.
Value types do not provide an overload for == by default. However, most of the value types provided by the framework provide their own overload. The default implementation of Equals for a value type is provided by ValueType, and uses reflection to make the comparison, which makes it significantly slower than a type-specific implementation normally would be. This implementation also calls Equals on pairs of references within the two values being compared.
关于必要的 C# 显式相等运算符实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1509524/
我正在使用 this solution在二进制矩阵中找到与图像边界对齐的矩形。假设现在我想找到一个不与图像边框对齐的矩形,并且我不知道它的方向;找到它的最快方法是什么? 为了示例,让我们寻找一个仅包含
else: 行在这个 Python 程序中是否正确/必要? from random import randrange for n in range(10): r = randrange(0,1
在 TDPL 7.1.5.1 中讨论了将 Widget w2 分配给 w1 并且作者指出“将 w2 逐个字段分配给 w1 会将 w2.array 分配给 w1.array——一个简单的数组边界分配,而
我是一名优秀的程序员,十分优秀!