How to implement IEquatable when mutable fields are part of the equality - Problem with GetHashCode

前端 未结 2 550
暗喜
暗喜 2021-01-24 05:21

I am using Entity Framework in my application.

I implemented with the partial class of an entity the IEquatable interface:

Partial          


        
2条回答
  •  不思量自难忘°
    2021-01-24 05:30

    Non-sealed classes should not implement IEquatable, because the only way to ensure that a derived class which overrides Object.Equals() and Object.GetHashCode() will implement IEquatable in a fashion consistent with Object.GetHashCode() is for the interface implementation to call the virtual Object.Equals(Object) method. Since the only purpose of IEquatable is to avoid the overhead of calling Object.Equals(Object), and a safe implementation of IEquatable on an unsealed class cannot avoid calling it, such an implementation would serve no purpose.

    Also, I would strongly counsel against any override of Object.Equals (or implementation of IEquatable) for any mutable class type. It is good for structs, whether mutable or not, to override Object.Equals and Object.GetHashCode, and to implement IEquatable, since the fields of a struct stored as e.g. a Dictionary key will be immutable even if the struct type exposes mutable public fields.

提交回复
热议问题