在“字典”中添加新的或更新现有项目的方法 [英] Method to Add new or update existing item in Dictionary
问题描述
在一些旧代码中,我已经看到以下扩展方法,以方便添加新的键值项目或更新该值,如果密钥已经存在。
方法-1(旧代码)。
public static void CreateNewOrUpdateExisting&TK; TValue>(
this IDictionary& TValue>地图,TKey键,TValue值)
{
if(map.ContainsKey(key))
{
map [key] = value;
}
else
{
map.Add(key,value);
}
}
虽然我已经检查过 map [key] = value
完全相同的作业。也就是说,这个方法可以用下面的方法-2替代。
方法2。
public static void CreateNewOrUpdateExisting< TKey,TValue>(
this IDictionary< TKey,TValue> map,TKey key,TValue value)
{
map [key] =值;
}
现在,我的问题是..如果我替换方法会有任何问题-1 by Method-2?是否会在任何可能的情况下破裂?
此外,我认为这曾经是HashTable和Dictionary之间的区别。 HashTable允许更新项目,或者通过使用索引器添加新项目,而Dictionary不会!在C#> 3.0版本中是否消除了这种差异?
如果用户再次发送相同的键值,此方法的目标不会太抛出异常,该方法应该使用新值更新条目,如果新的键值对已发送到该方法,则创建新条目。
blockquote>
如果我用Method-2替换Method-1,是否有任何问题?
不,只需使用 map [key] = value
。这两个选项是等价的。
关于词典<> ;
vs. Hashtable
:当您启动Reflector时,您会看到两个类的索引器设置器调用 this.Insert(键,值,/ * add * / false);
和 add
参数在插入重复键时负责抛出异常。所以这两个类的行为是一样的。
In some legacy code i have see the following extension method to facilitate adding a new key-value item or updating the value, if the key already exists.
Method-1 (legacy code).
public static void CreateNewOrUpdateExisting<TKey, TValue>(
this IDictionary<TKey, TValue> map, TKey key, TValue value)
{
if (map.ContainsKey(key))
{
map[key] = value;
}
else
{
map.Add(key, value);
}
}
Though, I have checked that map[key]=value
does exactly the same job. That is, this method could be replace with Method-2 below.
Method-2.
public static void CreateNewOrUpdateExisting<TKey, TValue>(
this IDictionary<TKey, TValue> map, TKey key, TValue value)
{
map[key] = value;
}
Now, my question is.. Could there be any problem if i replace Method-1 by Method-2? Will it break in any possible scenario?
Also, I think this used to be the difference between HashTable and Dictionary. HashTable allows updating an item, or adding a new item by using indexer while Dictionary does not!! Is this difference been eliminated in C# > 3.0 versions?
The objective of this method is not too throw exception if user sends the same key-value again, the method should just update the entry with the new value, and to make a new entry if new key-value pair has been send to the method.
Could there be any problem if i replace Method-1 by Method-2?
No, just use map[key] = value
. The two options are equivalent.
Regarding Dictionary<>
vs. Hashtable
: When you start Reflector, you see that the indexer setters of both classes call this.Insert(key, value, /* add */ false);
and the add
parameter is responsible for throwing an exception, when inserting a duplicate key. So the behavior is the same for both classes.
这篇关于在“字典”中添加新的或更新现有项目的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!