c# - 为什么我们在对 Dictionary 值进行操作时不对引用进行操作?
问题描述
为什么通过键从字典中检索到的对象不是引用?
我的测试代码:
class Program
{
static Dictionary<int, Salad> test = new Dictionary<int, Salad>();
static void Main(string[] args)
{
test.Add(1, new Salad() { Vegetables = Vegetables.Tomato });
test.Add(2, new Salad() { Vegetables = Vegetables.Tomato });
var newSalad = new Salad() { Vegetables = Vegetables.Carrot };
test[1] = newSalad;
var salad2 = test[2];
salad2 = newSalad;
Console.WriteLine(test[1].Vegetables);
//Write: Carrot
Console.WriteLine(test[2].Vegetables);
//Write: Tomato
Console.ReadLine();
}
}
public class Salad
{
public Vegetables Vegetables { get; set; }
}
public enum Vegetables
{
Tomato,
Potato,
Carrot
}
解决方案
您似乎对 c# 中的引用如何实际工作感到有些困惑。
为引用分配新值时,您更改了引用指向的实例,但对该实例的任何其他引用仍指向同一实例。
salad2
并且test[2]
都作为对同一个实例的引用开始,但是你有这一行:salad2 = newSalad;
。
此行不会更改存储在字典中的引用,它会更改salad2
引用并使其指向指向的同一Salad
实例newSalad
。
参考test[2]
没有改变。
如果您的代码有salad2.Vegetables = newSalad.Vegetables
,您将Tomato
参加两个Console.WriteLine()
电话。