如何避免字典中的空键错误?

ema*_*man 8 c# static-methods

如果key为null,如何避免错误?

//Getter/setter
public static Dictionary<string, string> Dictionary
{
    get { return Global.dictionary; }
    set { Global.dictionary = value; }
}
Run Code Online (Sandbox Code Playgroud)

更新:

Dictionary.Add("Key1", "Text1");
Dictionary["Key2"] <-error! so what can I write in the GET to avoid error?
Run Code Online (Sandbox Code Playgroud)

谢谢.

问候

Gro*_*ozz 17

用途TryGetValue:

Dictionary<int, string> dict = ...;
string value;

if (dict.TryGetValue(key, out value))
{
    // value found
    return value;
}
else
{
    // value not found, return what you want
}
Run Code Online (Sandbox Code Playgroud)

  • 这个答案是不正确的:如果键为null,`TryGetValue`会引发异常。 (2认同)
  • @Grozz 问题是如何避免在为字典中查找提供空键时出现错误。将空键传递给 `TryGetValue` 仍然会引发错误,因此它不会回答问题。在您的回答中,如果`key` 为空,则会引发异常,那么这如何解决原始问题?他试图避免例外。 (2认同)

Chr*_*isF 12

您可以使用该Dictionary.ContainsKey方法.

所以你写道:

if (myDictionary.ContainsKey("Key2"))
{
    // Do something.
}
Run Code Online (Sandbox Code Playgroud)

其他替代方法是将访问包装在一个try...catch块中或使用TryGetValue(请参阅链接到的MSDN页面上的示例).

string result = null;
if (dict.TryGetValue("Key2", out result))
{
    // Do something with result
}
Run Code Online (Sandbox Code Playgroud)

TryGetMethod,如果你想做些什么,结果因为你并不需要第二个电话来获取值(就像使用的是更有效的ContainsKey方法).

(当然,在这两种方法中,你都要用变量替换"Key2".)