Simplify Overriding Equals(), GetHashCode() in C# for Better Maintainability

前端 未结 3 1837
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-11 03:20

I find my self overriding Equals() and GetHashCode() frequently to implement the semantic that business objects with identical property values are

3条回答
  •  南方客
    南方客 (楼主)
    2020-12-11 03:57

    MSDN actually doesn't say "don't overload Equals et al for mutable types". It used to say that, but now it says:

    When you define a class or struct, you decide whether it makes sense to create a custom definition of value equality (or equivalence) for the type. Typically, you implement value equality when objects of the type are expected to be added to a collection of some sort, or when their primary purpose is to store a set of fields or properties.

    http://msdn.microsoft.com/en-us/library/dd183755.aspx

    Still, there are complexities surrounding stability of the hash code while an object participates in a hashed collection (Dictionary, HashSet, etc.).

    I decided to opt for the best of both worlds, as outlined here:

    https://stackoverflow.com/a/9752155/141172

提交回复
热议问题