即使在检查为null之后,Dictionary也会引发异常

sai*_*esh 4 .net c# dictionary exception-handling

我试图从字典中读取键的值,如下所示:

if (myDic["myKey"] != null)
{
}
Run Code Online (Sandbox Code Playgroud)

我可以看到我正在检查null,但即使这样它也会抛出KeyNotFoundException.我该怎么检查呢?请指教!

Jar*_*Par 9

看起来你混淆了HashTable那种行为Dictionary<TKey, TValue>.本HashTable类将返回null的时候,关键是不存在的,而价值Dictionary<TKey, TValue>会抛出异常.

您需要使用ContainsKeyTryGetValue避免此问题.

object value;
if (myDic.TryGetValue("apple", out value)) {
  ...
}
Run Code Online (Sandbox Code Playgroud)


Eri*_*rix 6

使用

if(mydic.ContainsKey("myKey"))
Run Code Online (Sandbox Code Playgroud)