这几天在找项目的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