如果键为空,如何避免错误?
//Getter/setter
public static Dictionary<string, string> Dictionary
{
get { return Global.dictionary; }
set { Global.dictionary = value; }
}
更新:
Dictionary.Add("Key1", "Text1");
Dictionary["Key2"] <-error! so what can I write in the GET to avoid error?
谢谢。
问候
最佳答案
使用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
}
关于c# - 如何避免字典中的空键错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4085983/