Sim*_*ver 3 c# generics extension-methods
我真的很讨厌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);
}
}
}
Run Code Online (Sandbox Code Playgroud)
这工作正常除了我似乎无法得到类型推断工作.
显然我希望能够做到以下几点:
var extraDataLookup = new Dictionary<string, string>();
extraDataLookup["zipcode"] = model.Zipcode;
Run Code Online (Sandbox Code Playgroud)
然后能够访问该值:
var zipcode = extraDataLookup.GetValueOrDefault("zipcode");
var foo = extraDataLookup.GetValueOrDefault("foo"); // should be null
Run Code Online (Sandbox Code Playgroud)
我已经看了一些关于类型推断的事情,将Jon Skeet的文章甚至源代码都反映System.Linq.Enumerable
在反射器中,但似乎缺少某些东西.
这有效:
extraDataLookup.GetValueOrDefault<string, string,string> ("foo")
Run Code Online (Sandbox Code Playgroud)
但事实并非如此
extraDataLookup.GetValueOrDefault ("foo")
Run Code Online (Sandbox Code Playgroud)
我该怎么办
PS.我只是在寻找泛型类型推理问题的解决方案,而不是任何其他建议.谢谢.
当您只需要两个泛型类型时,您似乎正在使用三种泛型类型定义扩展方法."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;
}
Run Code Online (Sandbox Code Playgroud)