سؤال

I have something like the following to be a key for a generic dictionary.

class IMyClass<T> : IEquatable<IMyClass> where T : struct
{
  //etc
}


class MyClass<T> : IMyClass<T> where T : struct
{
    public bool Equals(IRatingKey<T> other)
    {
       //etc
    }
}

From what I understand of EqualityComparer<T>.Default, it should see that I have implemented IEquatable<T> and therefore create an EqualityComparer on the fly.

Dictionary<TKey, TValue> requires an equality implementation to determine whether keys are equal. If comparer is null, this constructor uses the default generic equality comparer, EqualityComparer<T>.Default. If type TKey implements the System.IEquatable<T> generic interface, the default equality comparer uses that implementation.

However from what I see of using the dictionary indexer Dictionary<T>[], it still relies on overriding GetHashcode e.g public override int GetHashCode()

I can see that there are recommendations to override the lot for consistency, but I'm trying to understand it more. Is it because IEquatable should instead be directly on MyClass rather than in IMyClass? But I'd prefer it on the IMyClass so implementers need to be a dictionary key.

I'm experimenting with IEqualityComparer, but from what I understand I don't need it.

هل كانت مفيدة؟

المحلول

Dictionary always checks GetHashCode first, than goes forward to look into the elements of the bucket

Assume Dictionary as an Array with length L, on new element addition it calculates the appropriate index like

index = item.GetHashCode() % L

and put that element to the end of the appropriate bucket (just a model, in real word it also takes Abs, and re-build an array if necessary)

So in any point it have the following structure

---
 0  -> Item1, Item2
---
 1  -> Item3
---
 2 
---
...
---
L-1-> Item7

On lookup, dictionary calculates index again, and uses Equality to check only bucket elements of calculated index.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top