词典字典的扩展方法

spe*_*der 4 c# extension-methods dictionary

我正在尝试编写一个扩展方法,将数据插入到字典字典中,如下所示:

items=Dictionary<long,Dictionary<int,SomeType>>()
Run Code Online (Sandbox Code Playgroud)

到目前为止我所拥有的是:

    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);
    }
Run Code Online (Sandbox Code Playgroud)

但编译器不喜欢它.该声明:

items.LeafDictionaryAdd(longKey, intKey, someTypeValue);
Run Code Online (Sandbox Code Playgroud)

给我一个类型推断错误.

声明:

items.LeafDictionaryAdd<long, int, SomeType>(longKey, intKey, someTypeValue);
Run Code Online (Sandbox Code Playgroud)

我得到"...不包含...的定义,最好的扩展方法重载有一些无效的参数.

我究竟做错了什么?

Mar*_*ell 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);
}
Run Code Online (Sandbox Code Playgroud)