小測驗 Part1 public class Student
{
public string Name { get; private set; }
public int Tag { get; set; }
public Student(string name)
{
this.Name = name;
}
public void Show()
{
int iNum = 0;
Console.WriteLine($"This is {this.Name} {iNum} show!");
}
}
這時候,以下四個會放在Stack還是Heap?
student
Tag
Name
iNum
Student student = new Student("小昶");
student.Tag = 1;
student.Show();
答案:
student = Heap
Tag = Heap
Name = Heap
iNum = Stack
小測驗 Part2 public struct Salary
{
public int Base { get; set; }
public string Remark { get; set; }
public void Show()
{
string text = "2020年要消滅貧困人口,準備消失了!";
Console.WriteLine(text);
}
}
這時候,以下四個會放在Stack還是Heap?
salary
Base
Remark
text
Salary salary = new Salary();
salary.Base = 10000;
salary.Remark = "2020年貧困人口";
salary.Show();
答案:
salary = Stack
Base = Stack
Remark = Heap
text = Heap
結論:
參考型別一定會在HEAP裡面,實質型別要看依附的對象而決定
關於C#與IL對比解讀、GC的機制和優化之後會專門寫一篇文章跟大家講解
參考資料
鐵人賽文章