向字典中添加重复键会报错

来源:互联网 发布:光猫端口23失败 编辑:程序博客网 时间:2024/06/05 02:04

结论:向字典中添加相同的值键会抛出异常,所以在添加时,需要检验该字典是否已经包含该键。

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;


namespace ConsoleApp8

{

    classProgram

    {

        staticvoid Main(string[] args)

        {

            Dictionary<string,DateTime> date = newDictionary<string,DateTime>();

            try

            {

                AddUniqueKeyValue(ref date);

                AddEqualKeyValue(ref date);

            }

            catch (Exception ex )

            {

                Console.WriteLine(ex.ToString());

                Console.ReadKey();

            }

            foreach(KeyValuePair<string,DateTime> a in date)

            {

                Console.WriteLine(string.Format("{ 0}:{ 1}\r\n", a.Key, a.Value));

            }

            Console.ReadKey();

        }


        staticvoid AddUniqueKeyValue(refDictionary<string,DateTime> aDictionary)

        {

            for(int i =0; i<10; i++)

            {

                if(!aDictionary.ContainsKey(i.ToString()))

                    aDictionary.Add(i.ToString(),DateTime.Now.AddDays(-i));

            }

        }


        staticvoid AddEqualKeyValue(refDictionary<string,DateTime> a)

        {

            a.Add("1",DateTime.Now.AddDays(1));

        }

    }

}


运行后会抛出异常:

System.ArgumentException: 已添加了具有相同键的项。

   在 System.Collections.Generic.Dictionary`2.Insert(TKey key, TValue value, Boolean add)

   在 System.Collections.Generic.Dictionary`2.Add(TKey key, TValue value)

   在 ConsoleApp8.Program.AddEqualKeyValue(Dictionary`2& a) 位置 \\mac\home\documents\visual studio 2017\Projects\ConsoleApp8\ConsoleApp8\Program.cs:行号 42

   在 ConsoleApp8.Program.Main(String[] args) 位置 \\mac\home\documents\visual studio 2017\Projects\ConsoleApp8\ConsoleApp8\Program.cs:行号 17