C#:对象的 == 和 != 运算符的默认实现
我想知道相等运算符(== 和 !=)的默认实现
是什么?
public static bool operator ==(object obj1, object obj2)
{
return obj1.Equals(obj2);
}
public static bool operator !=(object obj1, object obj2)
{
return !obj1.Equals(obj2);
}
所以我只需要重写 Equals 方法,还是还需要重写等性运算符?
I'd like to know what is default implementation for equality operatort (== and !=)
Is it?
public static bool operator ==(object obj1, object obj2)
{
return obj1.Equals(obj2);
}
public static bool operator !=(object obj1, object obj2)
{
return !obj1.Equals(obj2);
}
So I only need to override Equals method or do I need to override euality operators as well ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
不,这不是 - 默认情况下,引用会被检查是否相等。
==
等运算符不是多态的,默认情况下不会调用任何多态的内容。例如:您不能覆盖相等运算符,但您可以重载它们,就像字符串一样。您是否应该是另一回事。我想如果我重写
Equals
,我通常会这样做,但不一定总是这样。No, it's not that - by default, references are checked for equality. Operators such as
==
are not polymorphic and don't call anything polymorphic by default. So for example:You can't override equality operators, but you can overload them, as string does. Whether or not you should is a different matter. I think I usually would if I were overriding
Equals
, but not necessarily always.C# 语言规范,第 7.9 节介绍了内置
==
运算符的确切行为。例如,当对引用类型值使用==
时,以下部分适用:请注意,“比较两个引用是否相等”并不意味着“调用
obj1.Equals(obj2)
的结果” em>”。这意味着两个引用必须指向同一个对象(引用相等)。The C# language specification, Section 7.9 covers the exact behavior of the built-in
==
operator. For example, when using==
on reference-type values, the following section applies:Note that "comparing two references for equality" does not mean "the result of calling
obj1.Equals(obj2)
". It means that both references must point to the same object (reference equality).默认情况下,这些运算符测试引用是否相等。
By default, those operators test for equality of reference.