2009-05-26 8 views
4
的词典扩展方法

我试图写一个扩展方法,将数据插入定义词典的词典如下:的字典

items=Dictionary<long,Dictionary<int,SomeType>>() 

我至今是:

public static void LeafDictionaryAdd<TKEY1,TKEY2,TVALUE>(this IDictionary<TKEY1,IDictionary<TKEY2,TVALUE>> dict,TKEY1 key1,TKEY2 key2,TVALUE value) 
    { 
     var leafDictionary = 
      dict.ContainsKey(key1) 
       ? dict[key1] 
       : (dict[key1] = new Dictionary<TKEY2, TVALUE>()); 
     leafDictionary.Add(key2,value); 
    } 

但编译器不喜欢它。声明:

items.LeafDictionaryAdd(longKey, intKey, someTypeValue); 

给我一个类型推断错误。

对于声明:

items.LeafDictionaryAdd<long, int, SomeType>(longKey, intKey, someTypeValue); 

我得到” ......不包含一个定义......和最佳推广方法重载有一些无效参数

我在做什么错。 ?

+0

这为我工作,当我试图它:| – mquander 2009-05-26 13:19:35

+0

Argh。多么痛苦。根本没有mods? – spender 2009-05-26 13:21:02

+1

哦,我把我的“项目”声明为IDictionary的IDictionary - 这可能是关键的区别。 – mquander 2009-05-26 13:24:44

回答

8

一些发明一般使用;-p

class SomeType { } 
static void Main() 
{ 
    var items = new Dictionary<long, Dictionary<int, SomeType>>(); 
    items.Add(12345, 123, new SomeType()); 
} 

public static void Add<TOuterKey, TDictionary, TInnerKey, TValue>(
     this IDictionary<TOuterKey,TDictionary> data, 
     TOuterKey outerKey, TInnerKey innerKey, TValue value) 
    where TDictionary : class, IDictionary<TInnerKey, TValue>, new() 
{ 
    TDictionary innerData; 
    if(!data.TryGetValue(outerKey, out innerData)) { 
     innerData = new TDictionary(); 
     data.Add(outerKey, innerData); 
    } 
    innerData.Add(innerKey, value); 
} 
2

尽量使用具体类型:

public static void LeafDictionaryAdd<TKEY1,TKEY2,TVALUE>(this IDictionary<TKEY1, Dictionary<TKEY2,TVALUE>> dict,TKEY1 key1,TKEY2 key2,TVALUE value) 

看到Dictionary<TKEY2,TVALUE>而不是IDictionary<TKEY2,TVALUE>

2

我猜这是一个协变/逆变问题。您的方法签名需要IDcitionaries的IDictionary,但是您将它传递给Dictionary的IDictionary。尝试使用具体的字典,而不是你的方法签名,为内部字典。

1

如果您在扩展方法的参数列表中指定了一个IDictionary, 那么您的项目将不匹配。

无论您的扩展名更改到

public static void LeafDictionaryAdd<TKEY1,TKEY2,TVALUE>(
    this IDictionary<TKEY1, Dictionary<TKEY2,TVALUE>> dict, 
    TKEY1 key1, 
    TKEY2 key2, 
    TVALUE value) 

或尝试和投你的项目

((IDictionary<long, IDictionary<int, YourType>>)items).LeafDictionaryAdd(l, i, o);