C#词典ValueOrNull / ValueorDefault

目前我正在使用

var x = dict.ContainsKey(key) ? dict[key] : defaultValue 

我想要一些方法让字典[key]为非耐用键返回null,所以我可以写类似的东西

 var x = dict[key] ?? defaultValue; 

这也是linq查询等的一部分,所以我更喜欢单行解决方案。

使用扩展方法:

 public static class MyHelper { public static V GetValueOrDefault(this IDictionary dic, K key, V defaultVal = default(V)) { V ret; bool found = dic.TryGetValue(key, out ret); if (found) { return ret; } return defaultVal; } void Example() { var dict = new Dictionary(); dict.GetValueOrDefault(42, "default"); } } 

您可以使用辅助方法:

 public abstract class MyHelper { public static V GetValueOrDefault( Dictionary dic, K key ) { V ret; bool found = dic.TryGetValue( key, out ret ); if ( found ) { return ret; } return default(V); } } var x = MyHelper.GetValueOrDefault( dic, key ); 

这是“终极”解决方案,因为它是作为扩展方法实现的,使用IDictionary接口,提供可选的默认值,并且简洁地编写。

 public static TV GetValueOrDefault(this IDictionary dic, TK key, TV defaultVal=default(TV)) { TV val; return dic.TryGetValue(key, out val) ? val : defaultVal; } 

不仅仅是TryGetValue(key, out value)你在寻找什么? 引用MSDN:

 When this method returns, contains the value associated with the specified key, if the key is found; otherwise, the default value for the type of the value parameter. This parameter is passed uninitialized. 

来自http://msdn.microsoft.com/en-us/library/bb347013(v=vs.90).aspx