As the title says: do I need to override the ==
operator? how about the .Equals()
method? Anything I'm missing?
相关问题
- Sorting 3 numbers without branching [closed]
- Graphics.DrawImage() - Throws out of memory except
- Generic Generics in Managed C++
- Why am I getting UnauthorizedAccessException on th
- 求获取指定qq 资料的方法
Unfortunetely I don't have enough reputation to comment other entries. So I'm posting possible enhancement to the top solution here.
Correct me, if i'm wrong, but implementation mentioned above
Has major flaw. I'm refering to
XORing is symmetrical, so Complex(2,1) and Complex(1,2) would give same hashCode.
We should probably make something more like:
You should also implement IEquatable<T>. Here is an excerpt from Framework Design Guidelines:
An example from msdn
Most of the time you can avoid implementing Equals and GetHashcode in structs - because there is an automatic implementation by the compiler for Value types using bitwise content + reflection for reference members.
Have a look at that post : Which is best for data store Struct/Classes?
So for ease of use you could still implement == and !=.
But most of the time you can avoid implementing Equals and GetHashcode.
A case where you'd have to implement Equals and GetHashCode is for a field that you don't wan't to take into account.
For instance a field that varies as time goes by like Age of a Person or instantSpeed of a car( the identity of the object shouldn't change if you want to find it back in the dictionary at the same place)
Regards, best code
Just for completness I would also advice to overload
Equals
method:this is a real spead improvement as there is no boxing occuring of the input argument of
Equals(Object obj)
methodSome best practices for using value types:
This comes from this post: http://theburningmonk.com/2015/07/beware-of-implicit-boxing-of-value-types/
The basic difference among the two is that the
==
operator is static, i.e. the appropriate method to invoke is determined at compile time, while theEquals
method is invoked dinamically on an instance.Defining both is probably the best thing to do, even if this matters less in the case of structs, since structs cannot be extended (a struct can't inherit from another).