词典中使用哪个IEqualityComparer? [英] Which IEqualityComparer is used in a Dictionary?
问题描述
让我们说我实例化这样的字典
var dictionary = new Dictionary<MyClass, SomeValue>();
MyClass是我自己的实现IEqualityComparer<>
的类.
现在,当我对字典进行操作(例如添加,包含,TryGetValue等)时,字典是否使用默认的EqualityComparer<T>.Default
,因为我从未将其传递给构造函数,还是使用了MyClass实现的IEqualityComparer?>
谢谢
它将使用默认的相等比较器.
如果一个对象能够与其他对象进行比较,那么它应该实现IEquatable
,而不是IEqualityComparer
.如果某个类型实现了IEquatable
,则它将用作EqualityCOmparer.Default
的实现,否则将使用object.Equals
和object.GetHashCode
方法.
IEqualityComparer
旨在比较 other 对象是否相等,而不是本身.
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
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.
这篇关于词典中使用哪个IEqualityComparer?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!