C#-Dictionary-字典学习

C#-Dictionary-字典学习

此段之后为正文,前面为格式设置color=#00f555f size=5 face=“黑体”

1.引入库

代码如下(示例):

<span style="color: #00ff7f;">// 修改注释颜色</span>
<font color=#0099ff size=5 face="黑体">color=#0099ff size=5 face="黑体"</font>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace 键值对Dictionary
{
    internal class Program
    {
        static void Main(string[] args)
        {
            Dictionary<string, Student> stuDic = new Dictionary<string, Student>(); //创建了唯一的字典
            Student stu = new Student();    //创建了唯一的Student对象
            for (int i = 0; i < 100; i++)
            {
                stu.Name = "s_" + i.ToString();
                stu.Score = i;
                stuDic.Add(stu.Name, stu);  //每次循环创建一个 键值对,故一共创建了100个键值对
            }
            Console.WriteLine(stuDic["s_80"].Name);
            Console.WriteLine(stuDic["s_80"].Score);    //指向了唯一的Student对象,输出99
            
			Console.WriteLine("============================================================");
			
            Dictionary<string, Student> stuDic_2 = new Dictionary<string, Student>(); //创建了唯一的字典
            string varName = "";
            for (int i = 0; i < 100; i++)   //i只在for循环中创建,循环完后自动注销
            {
                Student stu2 = new Student();   //创建了100个Student对象
                stu2.Name = "s2_" + i.ToString();   //对
                stu2.Score = 200 + i;
                varName = "varName"+i.ToString();
                stuDic_2.Add(varName, stu2);
            }
            Console.WriteLine(stuDic_2["varName80"].Name);
            Console.WriteLine(stuDic_2["varName80"].Score);
        }
    }
}
class Student
{
    public string Name;
    public int Score;
}

输出结果:
在这里插入图片描述

结论

特点:

只创建了一个 Student 对象:
在循环开始时,创建了一个 Student 对象 stu。
每次循环中,stu 的 Name 和 Score 属性被覆盖,但 stu 仍然是同一个对象。
字典中的所有值指向同一个对象:
由于 stu 是同一个对象,"stuDic 中的所有键值对的值实际上都是对 stu 的引用"。
最终,"字典中的所有 Student 对象都具有相同的属性值(即最后一次迭代时的 Name 和 Score)"。

总结:
这种写法会"导致字典中所有值都指向同一个 Student 实例",最后字典中的每个条目的 Name 和 Score 都是 "s_99"99。
示例输出: 如果执行 Console.WriteLine(stuDic["s_80"].Score);,结果为 99,而不是 80。
这种写法通常是错误的,除非开发者明确需要所有键值对引用同一个对象。

"字典不允许重复键":
如果尝试插入一个已经存在的键(例如 stuDic.Add("s_1", stu),当 "s_1" 已经存在时),字典会抛出 ArgumentException。
这段代码中不会发生这种情况,因为 stu.Name 始终是动态生成的,值由循环控制,确保了唯一性。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值