有时候我真的很讨厌IDictionary<TKey, TValue> [key]
如果键在字典中不存在,将抛出异常。
当然有TryGetValue()
,但这似乎针对性能而非可用性进行了优化。
所以我想,哦,我会为它做一个扩展方法——我做到了:
public static class CollectionExtensions
{
public static TType GetValueOrDefault<TKeyType, TValue, TType>(this IDictionary<TKeyType, TType> dictionary, TKeyType key)
{
TType value = default(TType);
// attempt to get the value of the key from the dictionary
// if the key doesn't exist just return null
if (dictionary.TryGetValue(key, out value))
{
return value;
}
else
{
return default(TType);
}
}
}
这工作正常,除了我似乎无法进行类型推断。
显然我希望能够执行以下操作:
var extraDataLookup = new Dictionary<string, string>();
extraDataLookup["zipcode"] = model.Zipcode;
然后能够访问值:
var zipcode = extraDataLookup.GetValueOrDefault("zipcode");
var foo = extraDataLookup.GetValueOrDefault("foo"); // should be null
我看过一些关于类型推断的东西,包括 Jon Skeet's article甚至是 System.Linq.Enumerable
的源代码在 reflector但似乎缺少了一些东西。
这个有效:
extraDataLookup.GetValueOrDefault<string, string,string> ("foo")
但这不是
extraDataLookup.GetValueOrDefault ("foo")
我应该做什么。
附言。我只是在寻找通用类型推断问题的解决方案,而不是任何其他建议。谢谢。
最佳答案
当您只需要两个泛型时,您似乎在定义扩展方法。 “TValue”和“TType”意思相同,不是吗?试试这个:
public static TValue GetValueOrDefault<TKey, TValue>(
this IDictionary<TKey, TValue> dictionary, TKey key)
{
TValue value;
// attempt to get the value of the key from the dictionary
dictionary.TryGetValue(key, out value);
return value;
}
关于c# - 编写泛型扩展方法时的类型推断问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/506003/