[英]Overriding GetHashCode and Equals on a class because it's used in a dictionary
I have been asked to override GetHashCode and Equals on a particular class because I am using instances of this class as the key (lookup) in a dictionary. 我被要求在特定类上覆盖GetHashCode和Equals,因为我使用此类的实例作为字典中的键(查找)。
I've noticed that the class itself does not contain any public properties and the private fields are reference types. 我注意到类本身不包含任何公共属性,私有字段是引用类型。 Mostly public methods and events. 主要是公共方法和事件。
Do I still need to override these methods? 我还需要覆盖这些方法吗? I haven't seen a problem so far during testing. 到目前为止我在测试过程中没有看到任何问题。 How is equality tested in this scenario? 在这种情况下如何测试平等? If I do nothing, is the default OK? 如果我什么都不做,默认好吗?
Thanks in advance. 提前致谢。
Then you can use the hash of the two private objects as the hash. 然后,您可以使用两个私有对象的哈希作为哈希。
hash1 ^ hash2;
And you can compare the values of the read only fields for equality. 并且您可以比较只读字段的值是否相等。
The idea is that two identical objects should be equal. 这个想法是两个相同的对象应该是相同的。
If you want each instance to be a unique dictionary key, you don't need to override Equals
and GetHashCode
at all. 如果希望每个实例都是唯一的字典键,则根本不需要重写Equals
和GetHashCode
。 By default, each instance will be a unique hash key . 默认情况下, 每个实例都是唯一的哈希键 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.