原始碼(source code)→編譯器→中繼語言(MSIL)→CLR→電腦看得懂的語言(Native code)
所以我們可以知道,CLR( Common Language Runtime ):是 .NET Framework 的虛擬機器元件 (virtual machine component),用來管理執行中的.NET程序。
實質型別:
bool
byte
char
decimal
double
enum
float
int
long
sbyte
short
struct
uint
ulong
ushort
參考型別:
class
interface
delegate
object
string
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
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的機制和優化
之後會專門寫一篇文章跟大家講解
Common Language Runtime (CLR) 概觀
本篇已同步發表至個人部落格
https://moushih.com/2022ithome24/