如果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)
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".)
| 归档时间: |
|
| 查看次数: |
14954 次 |
| 最近记录: |