定义运算符==而不定义Equals()或GetHashCode()有什么问题? [英] What's wrong with defining operator == but not defining Equals() or GetHashCode()?
问题描述
对于下面的代码
public struct Person
{
public int ID;
public static bool operator ==(Person a, Person b) { return a.Equals(b); }
public static bool operator !=(Person a, Person b) { return !a.Equals(b); }
}
为什么编译器会给我这些警告?
不定义下面的方法怎么办?
Why does the compiler give me these warnings?
What's wrong with not defining the methods below?
warning CS0660: 'Person' defines operator == or operator != but
does not override Object.Equals(object o)
warning CS0661: 'Person' defines operator == or operator != but
does not override Object.GetHashCode()
推荐答案
EDIT :此答案已得到纠正,除其他事项外,请注意用户定义的值类型不会生成==
,并提及 ValueType.Equals
的性能问题.
EDIT: This answer has been corrected, among other things to note that user-defined value types don't generate ==
, and to mention the performance issues with ValueType.Equals
.
通常,覆盖其中一个(但不是全部)会造成混淆.用户希望这两个语义都不会被覆盖,或者两者都被覆盖.
In general, overridding one, but not all, is confusing. The user expects neither to be overridden, or both to be, with the same semantics.
Microsoft针对此状态的建议(除其他事项外) ):
Microsoft's recommendations for this state (among other things):
每当实现Equals方法时,都要执行GetHashCode方法.这样可以使Equals和GetHashCode保持同步.
Implement the GetHashCode method whenever you implement the Equals method. This keeps Equals and GetHashCode synchronized.
每当实现相等运算符(==)时都重写Equals方法,并使它们执行相同的操作.
Override the Equals method whenever you implement the equality operator (==), and make them do the same thing.
在您的情况下,您有充分的理由服从Equals
(编译器不会自动实现==
)并仅覆盖这两个(==
/!=
).但是,由于ValueType.Equals
使用反射,因此仍然存在性能问题:
In your case, you have a valid reason to defer to Equals
(the compiler doesn't automatically implement ==
) and override only those two (==
/!=
). However, there's still a performance issue, since ValueType.Equals
uses reflection:
重写特定类型的Equals方法以改善 该方法的性能并更紧密地代表了该概念 类型相等."
"Override the Equals method for a particular type to improve the performance of the method and more closely represent the concept of equality for the type."
因此,仍然建议最后覆盖所有(==
/!=
/Equals
).当然,对于这种琐碎的结构,性能可能并不重要.
Thus, it's still recommended to override all (==
/!=
/Equals
) in the end. Of course, performance may not matter for this trivial struct.
这篇关于定义运算符==而不定义Equals()或GetHashCode()有什么问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!