问题
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