词典中使用哪个IEqualityComparer? [英] Which IEqualityComparer is used in a Dictionary?

查看:87
本文介绍了词典中使用哪个IEqualityComparer?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们说我实例化这样的字典

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

MyClass是我自己的实现IEqualityComparer<>的类.

现在,当我对字典进行操作(例如添加,包含,TryGetValue等)时,字典是否使用默认的EqualityComparer<T>.Default,因为我从未将其传递给构造函数,还是使用了MyClass实现的IEqualityComparer?

谢谢

解决方案

它将使用默认的相等比较器.

如果一个对象能够与其他对象进行比较,那么它应该实现IEquatable,而不是IEqualityComparer.如果某个类型实现了IEquatable,则它将用作EqualityCOmparer.Default的实现,否则将使用object.Equalsobject.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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆