添加到字典的不同方式 [英] Different ways of adding to Dictionary

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

问题描述

Dictionary.add(key, value)Dictionary[key] = value 有什么区别?

我注意到最后一个版本在插入重复键时不会抛出 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);
    }
}

这是添加方法:

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

我不会发布整个 Insert 方法,因为它很长,但是方法声明是这样的:

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);
    }

检查键是否已经存在,如果存在并且参数add为真,则抛出异常.

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天全站免登陆