Dictionary Keys.Contains vs.ContainsKey:它们在功能上是否等效? [英] Dictionary Keys.Contains vs. ContainsKey: are they functionally equivalent?
问题描述
我很想知道这两种功能在所有情况下是否等效.
I am curious to know if these two are functionally equivalent in all cases.
是否有可能通过更改字典的默认比较器使两者在功能上有所不同?
Is it possible that by changing the dictionary's default comparator that these two would be functionally different?
还,不是几乎保证Keys.Contains
慢吗?
Also, isn't Keys.Contains
almost guaranteed to be slower?
推荐答案
这两个函数的作用完全相同.
These two functions do exactly the same thing.
Keys.Contains
是因为Keys
是ICollection<TKey>
,它定义了Contains
方法.
标准的Dictionary<TKey, TValue>.KeyCollection
实现(类,而不是接口)将其定义为
Keys.Contains
exists because Keys
is an ICollection<TKey>
, which defines a Contains
method.
The standard Dictionary<TKey, TValue>.KeyCollection
implementation (the class, not the interface) defines it as
bool ICollection<TKey>.Contains(TKey item){
return dictionary.ContainsKey(item);
}
由于它是明确实现的,因此甚至不能直接调用它.
Since it's implemented explicitly, you can't even call it directly.
您将看到我在上面说明的接口,或者是LINQ Contains()
扩展方法,该方法也将调用本机实现,因为它实现了ICollection<T>
.
You're either seeing the interface, which is what I explained above, or the LINQ Contains()
extension method, which will also call the native implementation since it implements ICollection<T>
.
这篇关于Dictionary Keys.Contains vs.ContainsKey:它们在功能上是否等效?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!