我定义了一个像这样的自定义类型的字典,
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>.TryGetValue(TKey, TValue) Method
Gets the value associated with the specified key.
或
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/