gpt4 book ai didi

必要的 C# 显式相等运算符实现

转载 作者:太空狗 更新时间:2023-10-29 18:26:10 24 4
gpt4 key购买 nike

我明白了为我的对象显式实现 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com