Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
561 views
in Technique[技术] by (71.8m points)

c# - What's wrong with defining operator == but not defining Equals() or GetHashCode()?

For the code below

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()
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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's recommendations for this state (among other things):

  • 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.

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:

"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."

Thus, it's still recommended to override all (==/!=/Equals) in the end. Of course, performance may not matter for this trivial struct.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...