通常,当您创建 Dictionary
时,您必须首先通过在字典本身上调用 add 来添加 k/v 对。
我有一个 Dictionary
,其中 mycontainer
是其他对象的容器。我需要能够快速向 mycontainer 添加内容,所以我想也许我可以重载下标 operator[]
来动态创建一个 mycontainer
(如果没有的话)已经存在,然后允许我直接在其上调用 add ,如下所示:
mydictionnary["SomeName"].Add(myobject);
而无需在每次具有所述名称的容器时显式创建 mycontainer不字典中存在。
我想知道这是否是一个好主意,或者我应该显式创建新的 mycontainer 对象?
Normally when you create a Dictionary<Tkey, TValue>
you have to first go and add k/v pairs by calling add on the dictionary itself.
I have a Dictionary<string, mycontainer>
where mycontainer
is a container of other objects. I need to be able to add things to the mycontainer quickly so I thought maybe I can overload the subscript operator[]
to create a mycontainer
on the fly if it doesn't already exist and then allowing me to call add on it directly, as such:
mydictionnary["SomeName"].Add(myobject);
without explicitly having to go create mycontainer every time a container with the said name doesn't exist in the dictionary.
I wondered if this is a good idea or should I explicitly create new mycontainer objects?
发布评论
评论(3)
您应该创建自己的类来包装
Dictionary>
。索引器看起来像这样:
You should make your own class that wraps a
Dictionary<TKey, List<TItem>>
.The indexer would look like this:
不妨这样做
myCustomClass.Add( key, subkey, value );
这样代码就很容易理解,并且智能感知将指导它的使用。Might as well do
myCustomClass.Add( key, subkey, value );
so the code can be easily understood and intellisense will guide it's usage.我会选择显式代码 - 索引器的隐式重载并不是真正常见的情况,并且可能会在几个月后当其他人阅读您的代码时出现问题。
I would go for explicit code - implicit overloading of an indexer is not really a common situation and will probably bite in a few months time when someone else will be reading your code.