兩者皆自動管理物件生命週期,避免記憶體洩漏與過早釋放問題。
CLR 監管 IL 程式碼,預設為「安全程式碼」。需呼叫 Win32 API、使用指標等低層操作時,須標記 unsafe 區塊,開發者自負正確性責任。
unsafe static void Method()unsafe { ... }using System;
class UnsafeClass
{
unsafe static void PointyMethod()
{
int i = 10;
int* p = &i;
Console.WriteLine("*p = " + *p);
string address = "Pointer p = " + ((int)p).ToString("X");
Console.WriteLine(address);
}
static void StillPointy()
{
int i = 10;
unsafe
{
int* p = &i;
Console.WriteLine("*p = " + *p);
}
}
static void Main()
{
PointyMethod();
StillPointy();
}
}
PointyMethod 整個方法標記 unsafe;StillPointy 僅區塊標記。