开发者

Lookup extension method

开发者 https://www.devze.com 2023-04-03 02:12 出处:网络
Rather than create a whole new class implementing ILookup<T> is it possible to add an extension method to dictionary which caters for it? I\'m thinking something along the following:

Rather than create a whole new class implementing ILookup<T> is it possible to add an extension method to dictionary which caters for it? I'm thinking something along the following:

public static void LookupAdd(this Dictionary<T, List<V>> dict, T key, V item)
{
    if (!dict.ContainsKey(key))
    {
        dict.Add(key, new List<T>());
    }
    dict[key].Add(item);
}

This fails to compile saying it can't identify the types. I'm guessing that my generic parameters are too co开发者_StackOverflow社区mplex (particularly List<V>)


You have forgotten to add the generic parameter syntax:

 public static void LookupAdd<T, V>(this Dictionary<T, List<V>> dictionary, T key, V item)
 {
 }

The <T, V> is missing.


Try...

public static void LookupAdd<T,V>(this Dictionary<T, List<V>> dict, T key, V item)
{
    if (!dict.ContainsKey(key))
    {
        dict.Add(key, new List<V>());
    }
    dict[key].Add(item);
}

UPDATE:

Notice that you should have

new List<V>()

where you have

new List<T>()
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号