0
点赞
收藏
分享

微信扫一扫

【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";


举报

相关推荐

0 条评论