更新:2007 年 11 月
C# 有一個非常有趣的功能是,它支援不具型別安全的程式碼。一般而言,是由 Common Language Runtime (CLR) 負責監控 Microsoft Intermediate Language (MSIL) 程式碼的行為以及阻止可疑的作業。但是,當您希望直接存取低階功能 (例如 Win32 API 呼叫) 時,只要您能負責確認這類程式碼的作業正確無誤,便可允許您執行此動作。這種程式碼必須放置在原始程式碼中的 unsafe 區塊內。
unsafe 關鍵字
呼叫低階 API 的 C# 程式碼會使用指標算術或執行某些其他不好的作業,它必須放置在以 unsafe 關鍵字標記的區塊內。下列中的任何一項都可標記為 unsafe:
一整個方法
大括號中的程式碼區塊
個別的陳述式
下列範例示範了以上三個狀況的 unsafe 用法:
class TestUnsafe
{
unsafe static void PointyMethod()
{
int i=10;
int *p = &i;
System.Console.WriteLine("*p = " + *p);
System.Console.WriteLine("Address of p = {0:X2}\n", (int)p);
}
static void StillPointy()
{
int i=10;
unsafe
{
int *p = &i;
System.Console.WriteLine("*p = " + *p);
System.Console.WriteLine("Address of p = {0:X2}\n", (int)p);
}
}
static void Main()
{
PointyMethod();
StillPointy();
}
}
在這個程式碼中,整個 PointyMethod() 方法被標記為 unsafe 的原因是這個方法會宣告並且使用指標。當這個區塊再次使用指標時,StillPointy() 方法便會將程式碼區塊標記為 unsafe。
fixed 關鍵字
在 safe 程式碼中,當記憶體回收行程在執行組織和壓縮閒置資源的任務時,它可於存留期中任意移動物件。但是,如果您的程式碼使用了指標,則這個行為可能很容易導致未預期的結果,因此您可使用 fixed 陳述式來指示記憶體回收行程不要移動某些特定物件。
下列程式碼說明了使用 fixed 關鍵字是為了確保系統不會在執行 PointyMethod() 方法的程式碼區塊時移動陣列。請注意,fixed 只能在 unsafe 程式碼中使用:
class TestFixed
{
public static void PointyMethod(char[] array)
{
unsafe
{
fixed (char *p = array)
{
for (int i=0; i<array.Length; i++)
{
System.Console.Write(*(p+i));
}
}
}
}
static void Main()
{
char[] array = { 'H', 'e', 'l', 'l', 'o' };
PointyMethod(array);
}
}