<分区>
我发现自己现在在我的代码中经常使用当前模式
var dictionary = new Dictionary<type, IList<othertype>>();
// Add stuff to dictionary
var somethingElse = dictionary.ContainsKey(key) ? dictionary[key] : new List<othertype>();
// Do work with the somethingelse variable
或者有时
var dictionary = new Dictionary<type, IList<othertype>>();
// Add stuff to dictionary
IList<othertype> somethingElse;
if(!dictionary.TryGetValue(key, out somethingElse) {
somethingElse = new List<othertype>();
}
这两种方式感觉都很迂回。我真正想要的是
dictionary.GetValueOrDefault(key)
现在,我可以为字典类编写一个扩展方法来为我做这件事,但我认为我可能遗漏了一些已经存在的东西。那么,有没有一种方法可以在不为字典编写扩展方法的情况下以更“容易理解”的方式来做到这一点?