Ron*_*ald 3 c# dictionary scope
也许有点愚蠢的问题,但是c#的语法方式是什么?如果我从字典中检索值并且我不确定它们是否存在,我是否需要预先确定它们,所以如果它们存在,我可以在以后使用m?
示例(稍后我需要在代码中使用'string bla'):
string bla = null;
if (myDictionary.ContainsKey("unknownKey"))
{
bla = myDictionary["unknownKey"];
}
if (bla != null) { etc etc etc }
Run Code Online (Sandbox Code Playgroud)
我必须检查字典中的很多项目,还有一些更复杂的类型,所以这将是一个相当大的预先声明...
但我认为在这种情况下问问题是回答它... Cheerz!
对于像我这样的东西,我喜欢使用扩展方法:
public static class DictionaryExtensions
{
public static T1 ValueOrDefault<T, T1>(this IDictionary<T, T1> dictionary, T key)
{
if (key == null || dictionary == null)
return default(T1);
T1 value;
return dictionary.TryGetValue(key, out value) ? value : default(T1);
}
}
Run Code Online (Sandbox Code Playgroud)
然后你可以像这样使用它:
var bla = myDictionary.ValueOrDefault("unknownKey");
Run Code Online (Sandbox Code Playgroud)
我更喜欢这个
if (myDictionary.ContainsKey("unknownKey"))
{
var bla = myDictionary["unknownKey"];
//etc etc etc
}
else
{
//your code when the key doesn't exist
//sometimes this else is useless
}
Run Code Online (Sandbox Code Playgroud)
请注意,Dictionary(K,V) 可以有空值!想象
myDictionary.Add("unknownKey", null);
Run Code Online (Sandbox Code Playgroud)
编辑一般来说,检查bla == null不一样,因为即使键存在,myDictionary.ContainsKey值仍然可以是。null为了获得更好的性能,您应该始终.TryGetValue像这样使用:
string bla;
if (myDictionary.TryGetValue("unknownKey", out bla))
{
//the key exists
}
else
{
//the key doesn't exist
}
Run Code Online (Sandbox Code Playgroud)