加入词典的不同方法 [英] Different ways of adding to Dictionary

查看:121
本文介绍了加入词典的不同方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是什么在的区别Dictionary.add(键,值)词典[关键] =值

我注意到的最后一个版本没有抛出插入重复键时,但有的ArgumentException 任何理由,更喜欢第一个版本

I've noticed that the last version does not throw an ArgumentException when inserting a duplicate key, but is there any reason to prefer the first version?

修改:有没有人有这方面的信息的权威来源?我试过MSDN,却是一如既往白费力气:(

Edit: Does anyone have an authoritative source of information about this? I've tried MSDN, but it is as always a wild goose chase :(

推荐答案

性能几乎是100%相同你可以通过在Reflector.net打开类检查了这一点。

The performance is almost a 100% identical. You can check this out by opening the class in Reflector.net

这是该索引:

public TValue this[TKey key]
{
    get
    {
        int index = this.FindEntry(key);
        if (index >= 0)
        {
            return this.entries[index].value;
        }
        ThrowHelper.ThrowKeyNotFoundException();
        return default(TValue);
    }
    set
    {
        this.Insert(key, value, false);
    }
}

这是Add方法:

public void Add(TKey key, TValue value)
{
    this.Insert(key, value, true);
}

我不会发布整个插入方法,因为它是相当长的,但是方法声明是这样的:

I won't post the entire Insert method as it's rather long, however the method declaration is this:

private void Insert(TKey key, TValue value, bool add)

而在功能的进一步下降,这种情况发生:

And further down in the function, this happens:

if ((this.entries[i].hashCode == num) && this.comparer.Equals(this.entries[i].key, key))
{
    if (add)
    {
        ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_AddingDuplicate);
    }



其中检查该键已经存在,并且如果它与参数添加是真实的,它会抛出异常。

Which checks if the key already exists, and if it does and the parameter add is true, it throws the exception.

因此,对于所有目的和主意的性能是一样的。

So for all purposes and intents the performance is the same.

像其他一些提到,它是所有关于你是否需要检查,对于企图将相同的键两次。

Like a few other mentions, it's all about whether you need the check, for attempts at adding the same key twice.

对不起,冗长的文章中,我希望这没关系。

Sorry for the lengthy post, I hope it's okay.

这篇关于加入词典的不同方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆