【问题标题】:Difference of Dictionary.Add vs Dictionary[key]=value [duplicate]Dictionary.Add 与 Dictionary[key]=value 的区别 [重复]
【发布时间】:2012-07-19 09:04:47
【问题描述】:

Dictionary.Add 方法和索引器Dictionary[key] = value 有什么区别?

【问题讨论】:

  • 我来寻找是因为我担心旧版本的 C# 可能需要使用 .Add() 来添加元素,但显然不需要。

标签: c# .net


【解决方案1】:

添加 -> 如果字典中已存在项,则将项添加到字典中,将引发异常。

索引器或Dictionary[Key] => 添加或更新。如果字典中不存在该键,则将添加一个新项。如果键存在,则值将使用新值更新。


dictionary.add 将向字典中添加一个新项目,dictionary[key]=value 将为字典中的现有条目设置一个值,以针对一个键。如果键不存在,则 (indexer) 将在字典中添加该项目。

Dictionary<string, string> dict = new Dictionary<string, string>();
dict.Add("Test", "Value1");
dict["OtherKey"] = "Value2"; //Adds a new element in dictionary 
Console.Write(dict["OtherKey"]);
dict["OtherKey"] = "New Value"; // Modify the value of existing element to new value
Console.Write(dict["OtherKey"]);

在上面的例子中,首先dict["OtherKey"] = "Value2"; 将在字典中添加一个新值,因为它不存在,其次它会将值修改为新值。

【讨论】:

  • 而当密钥在dictionar[key]=value中不存在时?
  • @HenkHolterman,它将使用新键添加到字典中
  • Thaks Habib。但我们可以使用 dictionar[newkey]=value 添加新键。哪种方式更好?
  • @rsg,对于添加一个新项目,dictionary.add 是更好的选择,因为它会让你知道键是否已经存在于字典中,如果使用 dictionary[key],它将更新它密钥存在,否则会添加一个新的
  • 在使用 Add 方法时如果 key 已经存在会抛出 ArgumentException。
【解决方案2】:

Dictionary.Add 如果密钥已经存在则抛出异常。 [] 用于设置项目时不会(如果您尝试访问它以进行读取,则会这样做)。

x.Add(key, value); // will throw if key already exists or key is null
x[key] = value; // will throw only if key is null
var y = x[key]; // will throw if key doesn't exists or key is null

【讨论】:

    【解决方案3】:

    Add 的文档说明了这一点,我觉得:

    您还可以使用Item 属性通过设置Dictionary(Of TKey, TValue) 中不存在的键的值来添加新元素;例如,myCollection[myKey] = myValue(在 Visual Basic 中为myCollection(myKey) = myValue)。但是,如果 Dictionary(Of TKey, TValue) 中已存在指定的键,则设置 Item 属性会覆盖旧值。相比之下,Add 方法会在具有指定键的值已存在时引发异常。

    (注意Item属性对应索引器。)

    【讨论】:

      【解决方案4】:

      当键在字典中不存在时的行为是相同的:在这两种情况下都会添加该项目。

      当密钥已经存在时,行为会有所不同。 dictionary[key] = value 将更新映射到键的值,而 dictionary.Add(key, value) 将改为抛出 ArgumentException。

      【讨论】:

        【解决方案5】:

        dictionary.add 将项目添加到字典中,而 dictionary[key]=value 将值分配给已经存在的键。

        【讨论】:

        • dictionary[key]=value 如果键不存在,则添加键和值。所以它是一种添加或更新方式
        猜你喜欢
        • 1970-01-01
        • 2015-10-12
        • 1970-01-01
        • 2012-04-18
        • 2013-09-22
        • 1970-01-01
        • 1970-01-01
        • 2013-06-24
        • 1970-01-01
        相关资源
        最近更新 更多