问题:
This question already has an answer here: 这个问题在这里已有答案:
I find myself using the current pattern quite often in my code nowadays 我发现自己现在经常在我的代码中使用当前模式
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
Or sometimes 或者有时候
var dictionary = new Dictionary<type, IList<othertype>>();
// Add stuff to dictionary
IList<othertype> somethingElse;
if(!dictionary.TryGetValue(key, out somethingElse) {
somethingElse = new List<othertype>();
}
Both of these ways feel quite roundabout. 这两种方式都让人觉得很迂回。 What I really would like is something like 我真正想要的是这样的
dictionary.GetValueOrDefault(key)
Now, I could write an extension method for the dictionary class that does this for me, but I figured that I might be missing something that already exists. 现在,我可以为字典类编写一个扩展方法来为我做这个,但我想我可能会遗漏已经存在的东西。 SO, is there a way to do this in a way that is more "easy on the eyes" without writing an extension method to dictionary? 那么,有没有办法以更简单的方式做到这一点,而无需在字典中编写扩展方法?
解决方案:
参考一: https://en.stackoom.com/question/AulJ参考二: https://stackoom.com/question/AulJ