无法在C#中对Dictionary使用GetValueorDefault()

Ven*_*nky 5 c# dictionary xamarin.forms .net-standard

我已经定义了一个像这样的自定义类型的字典,

 public readonly Dictionary<PricingSection, View> _viewMappings = new Dictionary<PricingSection, View>();
Run Code Online (Sandbox Code Playgroud)

现在,当我尝试做

_viewMappings.GetValueOrDefault(section);
Run Code Online (Sandbox Code Playgroud)

部分是类型 PricingSection

我收到一个错误说

严重性代码描述项目文件行抑制状态错误CS1061"字典"不包含"GetValueOrDefault"的定义,并且没有可访问的扩展方法"GetValueOrDefault"接受类型为"Dictionary"的第一个参数(您是否缺少using指令或装配参考?)

我错过了什么?

AAA*_*ddd 12

我错过了什么?

您遗漏的事实Dictionary是不包含此名称的任何方法GetValueOrDefault

字典类

也许你在找

Dictionary.TryGetValue(TKey,TValue)方法

获取与指定键关联的值.

要么

ImmutableDictionary.GetValueOrDefault方法(IImmutableDictionary,TKey)

如果字典中存在匹配的键,则获取给定键的值.


但是你可以实现自己的

public static class Extensions
{
    public static TValue GetValueOrDefault<TKey, TValue>(this Dictionary<TKey, TValue> dict,TKey key)
      =>  dict.TryGetValue(key, out var value) ? value : default(TValue);
}
Run Code Online (Sandbox Code Playgroud)