c# - 无法在 C# 中将 GetValueOrDefault() 用于字典

标签 c# dictionary xamarin.forms .net-standard

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

 public readonly Dictionary<PricingSection, View> _viewMappings = new Dictionary<PricingSection, View>();

现在当我尝试做的时候

_viewMappings.GetValueOrDefault(section);

部分的类型为 PricingSection

我收到一个错误提示

Severity Code Description Project File Line Suppression State Error CS1061 'Dictionary' does not contain a definition for 'GetValueOrDefault' and no accessible extension method 'GetValueOrDefault' accepting a first argument of type 'Dictionary' could be found (are you missing a using directive or an assembly reference?)

我错过了什么吗??

最佳答案

Am i missing something ??

您错过了 Dictionary 不包含此名称的任何方法 GetValueOrDefault 的事实

Dictionary<TKey,TValue> Class

也许你正在寻找

Dictionary<TKey,TValue>.TryGetValue(TKey, TValue) Method

Gets the value associated with the specified key.

ImmutableDictionary.GetValueOrDefault<TKey, TValue> Method (IImmutableDictionary<TKey, TValue>, TKey)

Gets the value for a given key if a matching key exists in the dictionary.


但是你可以实现你自己的

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);
}

如果您使用以下任何一种,IReadOnlyDictionary 有扩展方法重载

  • NET 5.0 RC1

  • .NET 核心 3.1 3.0 2.2 2.1 2.0

  • .NET 标准 2.1

CollectionExtensions.GetValueOrDefault

Tries to get the value associated with the specified key in the dictionary

关于c# - 无法在 C# 中将 GetValueOrDefault() 用于字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53940405/

相关文章:

c# - 用C#读取outlook MSG文件中的书签

c# - 我如何获得 protobuf-net 序列化内容的明文表示?

C#:使用列表作为字典值。值不会存储在字典中

c# - 无法访问派生类中的基属性 (C#)

c# - Moq 简单示例所需 - 数据库连接和文件处理

c# - 从数组转换为 ICollection<T>

python - 使用递归更新嵌套字典值

c++ - C++ 中的映射导致错误

azure - 如何使用 Xamarin 流式传输存储在 Azure 存储 Blob 中的视频

Xamarin 形式 : IOS won't load webview