1. 程式人生 > 其它 >2021-01-26 c#值型別和引用型別在記憶體中的儲存

2021-01-26 c#值型別和引用型別在記憶體中的儲存

技術標籤:c#資料結構

c#值型別和引用型別在記憶體中的儲存

1.值型別,放在棧中。
2.引用型別分兩段:引用放在棧當中,資料放在堆中。
在這裡插入圖片描述
當我們使用引用型別賦值的時候,賦值的是引用型別的 “引用”。

class vector2
{
public float x;
}
///
/// 值和引用類在記憶體中的儲存
///
class Program
{
static void Main(string[] args)
{
vector2 tempA = new vector2();
tempA.x = 100;
vector2 tempB = new vector2();
tempB.x = 200;
tempB= tempA;

tempB.x = 300;
Console.WriteLine(tempA.x);//程式輸出:300
Console.ReadKey();
}
}
記憶體執行過程:
1.當進行引用型別賦值的時候,是將tempA和tempB的記憶體地址,也就是將引用進行資料的賦值操作。在這裡插入圖片描述
2.tempA賦值給tempB 時,將記憶體地址A賦值給內訓地址B
在這裡插入圖片描述
通過這一步驟的操作,tempA 和tempB所使用的的資料為同一記憶體資料,更改操作等都一致。所以即使是將tempB.x = 300,tempA.x的值也會是:300。