c# - 如果键不存在,C# Dictionary<int, int> 查找会发生什么情况?

标签 c# dictionary

我尝试检查 null 但编译器警告说这种情况永远不会发生。我应该寻找什么?

最佳答案

假设您希望在键确实存在时获取值,请使用 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 然后索引器让它查找键两次,这是毫无意义的。)

请注意,即使您使用引用类型,检查 null 也不起作用 - Dictionary<,> 的索引器如果您请求丢失的 key ,将抛出异常,而不是返回 null。 (这是 Dictionary<,>Hashtable 之间的一个很大的区别。)

关于c# - 如果键不存在,C# Dictionary<int, int> 查找会发生什么情况?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2138982/

相关文章:

c# - Autofac DI 并行.foreach

c# - 为什么不调用 GetVaryByCustomString

c# - 如何基于另一个 UserControl 使用 WinForms 创建一个 UserControl?

node.js - 如何在路由器中访问 i18n-express 字典?

python - 生成倒排索引

c++ - C++ 映射表中结构键的比较运算符

c# - 如何暂停Avalonedit的Undostack?

字典中的 Excel VBA 类

python - 比较两个具有列表类型值的字典

c# - 跟踪 .ToListing EF Linq 查询之前匹配的表达式数量