使用operator []动态创建字典项

Ton*_*ion 6 c# dictionary operators

通常,当你创建一个时,Dictionary<Tkey, TValue>你必须先通过调用字典本身的add来添加k/v对.

我有一个Dictionary<string, mycontainer>地方mycontainer是其他对象的容器.我需要能够快速地向mycontainer添加内容,所以我想也许我可以重载下标operator[]来创建一个动态mycontainer,如果它还不存在然后允许我直接调用add,就这样:

mydictionnary["SomeName"].Add(myobject); 每次在字典中不存在具有所述名称的容器时,无需明确地创建mycontainer.

我想知道这是一个好主意还是我应该明确创建新的mycontainer对象?

SLa*_*aks 5

你应该创建自己的包装类Dictionary<TKey, List<TItem>>.

索引器看起来像这样:

public List<TItem> this[TKey key] {
    get {
        List<TItem> retVal;
        if (!dict.TryGetValue(key, out retVal))
            dict.Add(key, (retVal = new List<TItem>(itemComparer)));
        return retVal;
    }
}
Run Code Online (Sandbox Code Playgroud)