简体   繁体   English

覆盖类上的GetHashCode和Equals,因为它在字典中使用

[英]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. 如果希望每个实例都是唯一的字典键,则根本不需要重写EqualsGetHashCode By default, each instance will be a unique hash key . 默认情况下, 每个实例都是唯一的哈希键

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 覆盖Equals和GetHashCode-派生类中的默认实现 - Overriding Equals and GetHashCode - default implementation in derived class 通过覆盖GetHashCode和Equals从IEqualityComparer &lt;&gt;派生外部类的优点 - Advantage of deriving external class from IEqualityComparer<> over overriding GetHashCode and Equals 等于使用。 GetHashCode不是 - Equals is used. GetHashCode is not 当用作字典中的键时,是否会覆盖结构导致装箱的GetHashCode? - Will overriding GetHashCode for a struct cause boxing when used as a key in a dictionary? static Object.Equals方法,GetHashCode的默认实现和Dictionary类 - static Object.Equals method, default implementation of GetHashCode and the Dictionary class 使用“external”GetHashCode和Equals for Dictionary - Use “external” GetHashCode and Equals for Dictionary 实现EqualityCompare与覆盖GetHashCode和Equals - Implementing EqualityCompare vs overriding GetHashCode and Equals 覆盖一个类型的Equals和GetHashCode,它有&#39;dibs&#39;? - Overriding the Equals and GetHashCode of a type, which has 'dibs'? C#,在重写GetHashCode和Equals时应考虑哪些类字段/成员? - C#, Which class fields/members should be considered when overriding GetHashCode and Equals? 使用自定义Equals()和GetHashCode()的Dictionary的最佳性能 - Optimal performance of Dictionary with custom Equals() and GetHashCode()
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM