请澄清以下内容。如果你不介意一些c#的低级解释和/或书籍,请。
为什么赋值给后的secondDog.breed属性(第三行),两个属性获得相同的值(firstDog)。和secondDog.Breed).
似乎只有secondDog应该显示&拉布拉多",而不是firstDog !!
static void Main(string[] args)
{
var firstDog = new Dog() { Breed = "Bulldog" };
var secondDog = firstDog;
secondDog.Breed = "Labrador"; // Magic happens here !!!
Console.WriteLine(firstDog.Breed); // Labrador (why ???)
Console.WriteLine(secondDog.Breed); // Labrador
}
class Dog
{
public string Breed { get; set; }
}
为什么在下面的代码中我得到的结果与上面的代码(狗的例子)不同
int num = 5;
int numb = num;
numb = 30;
Console.WriteLine(num); // 5 (Not 30 like in the above Dog example)
Console.WriteLine(numb); // 30
这就是引用类型和值类型在操作中的区别。
Value类型将数据值保存在自己的内存空间中。它表示一个变量包含一个值。
int num = 5; // value type. We have created a value in memory
int numb = num; // here numb is 5. It is not pointing to `num`
// it just copies value of `num`. `numb` has own value 5 in
// memory. We created the second value in memory. Here we have
// two values in memory.
numb = 30; // here num is 30
但是,引用类型并不直接存储其值。它存储存储值的地址。也就是说,引用类型有一个指向保存数据的另一个内存位置的指针。
var firstDog = new Dog() { Breed = "Bulldog" }; // reference type
// We've created one object in memory
var secondDog = firstDog; // here you are assigning reference of
// "firstDog" to "secondDog". We still have one object on
// memory. We have not created new object in memory
secondDog.Breed = "Labrador"; // Here you are reading the address
// of object which points to the object created in the first row of
// this code snippet
在这里阅读更多关于引用类型和值类型的区别