【C#】字典Dictionary添加元素,除了使用Add还可以这样?

        // 01, 初始化的时候进行赋值
        Dictionary<int, string> dic = new Dictionary<int, string>() { { 1, "str111" } };
        // 02, 使用Add添加
        dic.Add(2, "str222");
        // 03, 直接指定Key值进行赋值
        dic[3] = "str333";

        //----------

        //获取未赋值Key, 报错
        string str4 = dic[4];  //KeyNotFoundException: The given key was not present in the dictionary

        // 01
        //避免报错, 先判断是否包含Key值
        if (dic.ContainsKey(4))
            str4 = dic[4];
        else
            str4 = string.Empty;

        // 02
        //TryGetValue获取未赋值Key, 值为Null
        string str5 = "str555";
        dic.TryGetValue(4, out str5);
        Debug.Log(str5);        // 输出"Null"

        //----------

        //添加新元素, 已存在key值, 报错
        dic.Add(2, "str666");   //ArgumentException: An item with the same key has already been added. Key: 2

        // 01
        //避免报错, 先判断是否包含Key值
        if (dic.ContainsKey(2))
            dic[2] = "str666";
        else
            dic.Add(2, "str666");

        // 02
        //赋值: 若不存在该Key, 添加新元素, 若已存在key, 重新赋值
        dic[2] = "str666";
        dic[5] = "str666";
发布了104 篇原创文章 · 获赞 74 · 访问量 7万+

猜你喜欢

转载自blog.csdn.net/qq_39108767/article/details/103682768
今日推荐