Overriding GetHashCode for mutable objects?

前端 未结 5 1416
野性不改
野性不改 2020-11-29 21:51

I\'ve read about 10 different questions on when and how to override GetHashCode but there\'s still something I don\'t quite get. Most implementations of

5条回答
  •  时光取名叫无心
    2020-11-29 22:29

    The underlying topic here is how to best uniquely identify objects. You mention serialization/deserialization which is important because referential integrity is lost in that process.

    The short answer, Is that objects should be uniquely identified by the smallest set of immutable fields that can be used to do so. These are the fields you should use when overrideing GetHashCode and Equals.

    For testing it's perfectly reasonable to define whatever assertions you need, usually these are not defined on the type itself but rather as utility methods in the test suite. Maybe a TestSuite.AssertEquals(MyClass, MyClass) ?

    Note that GetHashCode and Equals should work together. GetHashCode should return the same value for two objects if they are equal. Equals should return true if and only if two objects have the same hash code. (Note that it's possible that two object may not be equal but may return the same hash code). There are plenty of webpage that tackle this topic head-on, just google away.

提交回复
热议问题