C#字典< int,int>会发生什么如果密钥不存在查找? [英] What happens to C# Dictionary<int, int> lookup if the key does not exist?
问题描述
我尝试检查null,但编译器警告这种情况永远不会发生。我应该寻找什么?
I tried checking for null but the compiler warns that this condition will never occur. What should I be looking for?
推荐答案
假设你想获得价值,如果密钥 存在,请使用 词典< TKey,TValue> .TryGetValue
:
Assuming you want to get the value if the key does exist, use Dictionary<TKey, TValue>.TryGetValue
:
int value;
if (dictionary.TryGetValue(key, out value))
{
// Key was in dictionary; "value" contains corresponding value
}
else
{
// Key wasn't in dictionary; "value" is now 0
}
(使用 ContainsKey
然后索引器使它看起来两次,这是非常无意义的。)
(Using ContainsKey
and then the the indexer makes it look the key up twice, which is pretty pointless.)
注意,即使你 / em>使用引用类型,检查null将不起作用 - Dictionary<,>
的索引器将抛出异常,如果您请求缺少的键,而不是返回空值。 (这是 Dictionary<,>
和 Hashtable
之间的一个很大的区别。)
Note that even if you were using reference types, checking for null wouldn't work - the indexer for Dictionary<,>
will throw an exception if you request a missing key, rather than returning null. (This is a big difference between Dictionary<,>
and Hashtable
.)
这篇关于C#字典< int,int>会发生什么如果密钥不存在查找?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!