I really hate sometimes how IDictionary<TKey, TValue> [key]
will throw an exception if the key doesn't exist in the dictionary.
我真的很讨厌如果字典中不存在密钥,IDictionary
Of course there is TryGetValue()
, but that seems to have been optimized for performance and not usability.
当然有TryGetValue(),但似乎已针对性能而非可用性进行了优化。
So I thought, oh I'll just make an extension method for it - which I did :
所以我想,哦,我只是为它做一个扩展方法 - 我做了:
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);
}
}
}
This works fine EXCEPT I cannot seem to get type inference working.
这工作正常除了我似乎无法得到类型推断工作。
Obviously I want to be able to do the following :
显然我希望能够做到以下几点:
var extraDataLookup = new Dictionary<string, string>();
extraDataLookup["zipcode"] = model.Zipcode;
and then be able to access the value :
然后能够访问该值:
var zipcode = extraDataLookup.GetValueOrDefault("zipcode");
var foo = extraDataLookup.GetValueOrDefault("foo"); // should be null
I've looked at a few things about type inference, inlucing Jon Skeet's article and even sourcecode to System.Linq.Enumerable
in reflector but seem to be missing something.
我已经看了几个关于类型推断的事情,将Jon Skeet的文章甚至源代码都反映到了反射器中的System.Linq.Enumerable,但似乎缺少了一些东西。
This works :
这有效:
extraDataLookup.GetValueOrDefault<string, string,string> ("foo")
but this doesn't
但事实并非如此
extraDataLookup.GetValueOrDefault ("foo")
What should I be doing.
我该怎么办
PS. I'm only looking for solutions to the generic type inference problem, not any other suggestions. Thanks.
PS。我只是在寻找泛型类型推理问题的解决方案,而不是任何其他建议。谢谢。
1 个解决方案
#1
You seem to be defining your extension method with three generic types when you only need two. "TValue" and "TType" mean the same thing, don't they? Try this:
当您只需要两个泛型类型时,您似乎正在使用三种泛型类型定义扩展方法。 “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;
}
#1
You seem to be defining your extension method with three generic types when you only need two. "TValue" and "TType" mean the same thing, don't they? Try this:
当您只需要两个泛型类型时,您似乎正在使用三种泛型类型定义扩展方法。 “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;
}