简体   繁体   中英

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.

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. By default, each instance will be a unique hash key .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM