Addition (i.e. +) extension method with a generic C# Dictionary
I'm trying to write a generic Dictionary extension method like so. TValue will always be an int but TKey could be a string or a DateTime.
public static void AddOrIncrement<TKey, TValue>(this Dictionary<TKey, TValue> dict, TKey key, TValue value)
{
if (!dict.ContainsKey(key))
{
dict.Add(key, value);
}
else
{
dict[key] += value;
}
}
But this won't compile - Operator '+=' cannot be applied to operands of type 'TValue' and 'TValue'.
So then I try:
public static void AddOrIncrement<TKey, TValue>(this Dictionary&l开发者_Go百科t;TKey, TValue> dict, TKey key, TValue value) where TValue : int
but that doesn't compile either. So then I tried:
public static void AddOrIncrement<TKey, int>(this Dictionary<TKey, int> dict, TKey key, int value)
which doesn't compile - "Type parameter declaration must be an identifier not a type"
Try:
public static void AddOrIncrement<TKey>(this Dictionary<TKey, int> dict, TKey key, int value)
You're trying to make an extension method that takes only one generic parameter:
public static void AddOrIncrement<TKey>(this Dictionary<TKey, int> dict, TKey key, int value)
精彩评论