Dictionary Keys.Contains vs. ContainsKey: are they functionally equivalent?

前端 未结 2 1383
心在旅途
心在旅途 2020-12-06 16:20

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

2条回答
  •  孤城傲影
    2020-12-06 16:55

    These two functions do exactly the same thing.

    Keys.Contains exists because Keys is an ICollection, which defines a Contains method.
    The standard Dictionary.KeyCollection implementation (the class, not the interface) defines it as

    bool ICollection.Contains(TKey item){ 
        return dictionary.ContainsKey(item); 
    }
    

    Since it's implemented explicitly, you can't even call it directly.


    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.

提交回复
热议问题