关于C#引用的一些坑

这几天在找项目的bug发现前辈的引用写法有些问题,导致数据不同步。
所以写一篇文章记录一下:
C#里面有很好用的各种容器,list dictionary等等,但是我们普通用法就是以一些值类型或者“string”来作为key,但是项目一旦大了,key可能就是一个复杂的引用类型。


```csharp
using System;
using System.Collections;
using System.Collections.Generic;

namespace test2021_2_25
{
    class job
    {
        public string jobname;
        public job(string jobname)
        {
            this.jobname = jobname;
        }
    }
    class people
    {
        public string peoplename;
        public job _job;
        public people(string name,string jobname)
        {
            this.peoplename = name;
            this._job = new job(jobname);
        }
        public people(string name,job j)
        {
            this.peoplename = name;
            this._job = j;
        }
    }
    class Program
    {
        static void Main(string[] args)
        {

            //Dictionary<people, job> dic = new Dictionary<people, job>();
            job peaky = new job("peakyblinders");
            people auther = new people("auther", peaky);
            people tom = new people("tom", peaky);
            people thomas = tom;
            job thomasjob = thomas._job;
            tom._job = new job("politician");

            Console.WriteLine(ReferenceEquals(tom, thomas));
            Console.WriteLine(ReferenceEquals(tom._job, thomas._job));
            Console.WriteLine(ReferenceEquals(tom._job, thomasjob));
        }
    }
}
true 
true
false
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值