C#字典< int,int>会发生什么如果密钥不存在查找? [英] What happens to C# Dictionary<int, int> lookup if the key does not exist?

查看:155
本文介绍了C#字典< int,int>会发生什么如果密钥不存在查找?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试检查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#字典&lt; int,int&gt;会发生什么如果密钥不存在查找?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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