What needs to be done to use the value of the reference type as a dictionary key?

Suppose I have a class Tthat I want to use as a key in a collection Dictionary<T,U>.

What should I implement in Tso that these keys are based on values T, not references T?

I hope this is easy GetHashCode().

+3
source share
4 answers

You must implement GetHashCode () and Equals ().

The dictionary is a Hashtable under the covers, so you can read this: Peer Traps / GetHashCode - How does the hash table work?

+5
source

IEqualityComparer<T> , EqualityComparer<T>.Default, MSDN :

Default , T System.IEquatable(Of T) , , EqualityComparer (Of T), . , EqualityComparer (Of T), Object.Equals Object.GetHashCode, T.

, IEquatable<T> ( , Equals GetHashCode) .

+3

Equals GetHashCode, IEqualityComparer<T>, .

IEqualityComparer<T>: - - . , . , , IEquatable<T> ... . ( IEqualityComparer<T> , , .)

+3

Equals(object obj). , GetHashCode Equals. MSDN.

+2

Source: https://habr.com/ru/post/1746550/


All Articles