Dan*_*ain 60 c# exception keynotfoundexception
我正在使用字典来执行我正在处理的程序的查找.我在字典中运行了一堆密钥,我希望某些密钥没有值.我抓住KeyNotFoundException它发生的右边,然后吸收它.所有其他异常将传播到顶部.这是处理这个问题的最佳方法吗?或者我应该使用不同的查找?该字典使用int作为其键,并使用自定义类作为其值.
Jon*_*eet 110
Dictionary<int,string> dictionary = new Dictionary<int,string>();
int key = 0;
dictionary[key] = "Yes";
string value;
if (dictionary.TryGetValue(key, out value))
{
Console.WriteLine("Fetched value: {0}", value);
}
else
{
Console.WriteLine("No such key: {0}", key);
}
Run Code Online (Sandbox Code Playgroud)
Pet*_*ter 34
尝试使用:Dict.ContainsKey
编辑:
性能明智我认为Dictionary.TryGetValue更好,因为其他一些建议,但我不喜欢使用Out,当我不必如此在我看来ContainsKey更可读但如果你还需要更多的代码行.
Jer*_*vak 24
一线解决方案使用 TryGetValue
string value = dictionary.TryGetValue(key, out value) ? value : "No key!";
Run Code Online (Sandbox Code Playgroud)
请注意,值变量必须是字典在此案例字符串中返回的类型.在这里你不能使用var作为变量声明.
如果您正在使用C#7,在这种情况下,你的CAN包括var和内联定义它:
string value = dictionary.TryGetValue(key, out var tmp) ? tmp : "No key!";
Run Code Online (Sandbox Code Playgroud)
Mon*_*per 16
这是一个单行解决方案(请记住,这会使查找两次.请参阅下面的tryGetValue版本,该版本应该在长时间运行的循环中使用.)
string value = dictionary.ContainsKey(key) ? dictionary[key] : "default";
Run Code Online (Sandbox Code Playgroud)
然而,每当我访问字典时,我发现自己必须这样做.我希望它返回null所以我可以写:
string value = dictionary[key] ?? "default";//this doesn't work
Run Code Online (Sandbox Code Playgroud)
您应该使用Dictionary的'ContainsKey(string key)'方法来检查密钥是否存在.使用正常程序流程的例外不被视为一种好的做法.
我知道这是一个旧线程,但如果它有帮助,先前的答案很好,但是可以解决复杂性的评论和乱扔代码的担忧(对我来说也都有效)。
我使用自定义扩展方法以更优雅的形式包装上述答案的复杂性,这样它就不会在整个代码中散落一地,然后它为空合并运算符提供了很好的支持。. . 同时也最大限度地提高性能(通过上述答案)。
namespace System.Collections.Generic.CustomExtensions
{
public static class DictionaryCustomExtensions
{
public static TValue GetValueSafely<TKey, TValue>(this IDictionary<TKey, TValue> dictionary, TKey key)
{
TValue value = default(TValue);
dictionary.TryGetValue(key, out value);
return value;
}
}
}
Run Code Online (Sandbox Code Playgroud)
然后你可以简单地通过导入命名空间System.Collections.Generic.CustomExtensions来使用它
string value = dictionary.GetValueSafely(key) ?? "default";
Run Code Online (Sandbox Code Playgroud)