我正在使用一个字典来执行一个程序的查找,我正在工作。我在字典中运行了一些键,我希望有些键没有值。我在 KeyNotFoundException发生的地方抓住它,然后吸收它。所有其他异常都将传播到顶部。这是最好的解决办法吗?或者我应该用另一种查找方式?字典使用 int 作为其键,使用自定义类作为其值。
KeyNotFoundException
尝试使用: Dict.ContainsKey
编辑: 在性能方面,我认为 Dictionary.TryGetValue更好,因为一些其他建议,但我不喜欢使用时,我不必如此,在我看来 ContainsKey 是更具可读性,但需要更多的代码行,如果你需要的价值也。
Dictionary.TryGetValue
改为使用 Dictionary.TryGetValue:
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); }
您应该使用 Dictionary 的“ ContainsKey (string key)”方法来检查密钥是否存在。 对正常的程序流使用异常不被认为是一种好的做法。
这里有一个单行解决方案(请记住,这会进行两次查找。请参见下面的 tryGetValue 版本,它应该在长时间运行的循环中使用。)
string value = dictionary.ContainsKey(key) ? dictionary[key] : "default";
然而,我发现自己每次查字典时都不得不这样做。我更希望它返回 null,这样我就可以写:
string value = dictionary[key] ?? "default";//this doesn't work
使用 TryGetValue的一行解决方案
TryGetValue
string value = dictionary.TryGetValue(key, out value) ? value : "No key!";
请注意,价值变量的类型必须是 dictionary 在这种情况下返回的 绳子类型。这里不能使用 Var进行变量声明。
如果您使用的是 C # 7,在这种情况下,可以包含 var 并内联地定义它:
string value = dictionary.TryGetValue(key, out var tmp) ? tmp : "No key!";
这里还有一个很好的扩展方法,它可以完全满足你想要达到的目标。GetOrDefault (“ Key”)或 dict。GetOrDefault (“键”,“无值”)
public static TValue GetOrDefault<TKey, TValue>(this Dictionary<TKey, TValue> dictionary, TKey key, TValue defaultValue = default(TValue)) { if (dictionary != null && dictionary.ContainsKey(key)) { return dictionary[key]; } return defaultValue; }
我知道这是一个老线程,但如果它是有帮助的,以前的答案是伟大的,但复杂的意见和乱丢代码的关注(对我来说也是有效的)可以解决。
我使用一个自定义的扩展方法将上述答案的复杂性以一种更优雅的形式包装起来,这样就不会在整个代码中杂乱无章,然后它就可以支持 null 合并操作符... ... 同时还可以最大化性能(通过上面的答案)。
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; } } }
然后,您可以通过导入名称空间 系统。集合。通用。自定义扩展来使用它
string value = dictionary.GetValueSafely(key) ?? "default";