Which IEqualityComparer is used in a Dictionary?

可紊 提交于 2020-02-22 22:10:21

问题


Lets say I instantiate a dictionary like this

var dictionary  = new Dictionary<MyClass, SomeValue>();

And MyClass is my own class that implements an IEqualityComparer<>.

Now, when I do operations on the dictionary - such as Add, Contains, TryGetValue etc - does dictionary use the default EqualityComparer<T>.Default since I never passed one into the constructor or does it use the IEqualityComparer that MyClass implements?

Thanks


回答1:


It will use the default equality comparer.

If an object is capable of comparing itself for equality with other objects then it should implement IEquatable, not IEqualityComparer. If a type implements IEquatable then that will be used as the implementation of EqualityCOmparer.Default, followed by the object.Equals and object.GetHashCode methods otherwise.

An IEqualityComparer is designed to compare other objects for equality, not itself.




回答2:


It will use IEqualityComparer<T>.Default if you don't specify any equality comparer explicitly.

This default equality comparer will use the methods Equals and GetHashCode of your class.

Your key class should not implement IEqualityComparer, this interface should be implemented when you want to delegate equality comparisons to a different class. When you want the class itself to handle equality comparisons, just override Equals and GetHashCode (you can also implement IEquatable<T> but this is not strictly required).




回答3:


If you want to use IEquatable<T> you can do so without having to create a separate class but you do need to implement GetHashCode().

It will pair up GetHashCode() and bool Equals(T other) and you don't have to use the archaic Equals signature.

// tested with Dictionary<T>
public class Animal : IEquatable<Animal>
{
    public override int GetHashCode()
    {
        return (species + breed).GetHashCode();
    }

    public bool Equals(Animal other)
    {
        return other != null &&
               (
                  this.species == other.species &&
                  this.breed == other.breed &&
                  this.color == other.color                   
               );
    }
}


来源:https://stackoverflow.com/questions/25853384/which-iequalitycomparer-is-used-in-a-dictionary

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!