Bas*_*sin 1 c# collections dictionary
我有一个值为整数类型的字典。当我使用 type 的属性之一填充我的类时Nullable<int>
,我想根据给定的产品 ID 使用字典中的值填充此属性。
当给定的产品 ID 没有相应的值时,如何获得可为空类型?
public class OrderLine
{
public int? AvailableQuantity { get; set; }
}
var selectedProductId = Guid.NewGuid();
var products = new Dictionary<Guid, int>
{
{ Guid.NewGuid(), 1 },
{ Guid.NewGuid(), 2 },
{ Guid.NewGuid(), 3 },
};
var result = new OrderLine
{
Id = Guid.NewGuid(),
ProductId = selectedProductId,
AvailableQuantity = products.GetValueOrDefault(selectedProductId, default)
};
Run Code Online (Sandbox Code Playgroud)
上面的方法返回0
而不是null
当我尝试时,编译器无法编译
AvailableQuantity = products.GetValueOrDefault(selectedProductId, default(int?))
Run Code Online (Sandbox Code Playgroud)
无法从用法推断方法“TValue System.Collections.Generic.CollectionExtensions.GetValueOrDefault(this IReadOnlyDictionary, TKey, TValue)”的类型参数。尝试明确指定类型参数。
我无法更改字典的类型。字典是一种广泛使用的返回类型方法。这是我们需要处理产品 id 不能在该字典中的第一种情况。
我想避免枚举字典以将其类型更改为可空
您可以编写一个使用TryGetValue的 C# 扩展
例如
public static class DictionaryExtensions
{
public static TValue? GetValueOrNull<TKey, TValue>(this IDictionary<TKey, TValue> dict, TKey key)
where TValue : struct
{
if (dict.TryGetValue(key, out TValue value))
{
return value;
}
return null;
}
}
Run Code Online (Sandbox Code Playgroud)
用法:
products.GetValueOrNull(selectedProductId);
Run Code Online (Sandbox Code Playgroud)
PS:这个扩展也适用于其他类型int
,例如decimal
,bool
和其他结构类型
归档时间: |
|
查看次数: |
195 次 |
最近记录: |