unsafe (C# 參考)

unsafe 關鍵字表示任何與指標有關的作業都需要的不安全內容。 如需詳細資訊,請參閱 Unsafe 程式碼和指標

您可以在類型或成員的宣告中使用 unsafe 修飾詞。 類型或成員的整個文字範圍因此視為不安全內容。 例如,下列是使用 unsafe 修飾詞所宣告的方法︰

unsafe static void FastCopy(byte[] src, byte[] dst, int count)
{
    // Unsafe context: can use pointers here.
}

不安全內容的範圍是從參數清單延伸到方法結尾,因此也可以在參數清單中使用指標︰

unsafe static void FastCopy ( byte* ps, byte* pd, int count ) {...}

您也可以使用不安全區塊,以在這個區塊內使用不安全程式碼。 例如:

unsafe
{
    // Unsafe context: can use pointers here.
}

若要編譯不安全的程式碼,您必須指定 AllowUnsafeBlocks 編譯器選項。 Common Language Runtime 不會驗證不安全的程式碼。

範例

// compile with: -unsafe
class UnsafeTest
{
    // Unsafe method: takes pointer to int.
    unsafe static void SquarePtrParam(int* p)
    {
        *p *= *p;
    }

    unsafe static void Main()
    {
        int i = 5;
        // Unsafe method: uses address-of operator (&).
        SquarePtrParam(&i);
        Console.WriteLine(i);
    }
}
// Output: 25

C# 語言規格

如需詳細資訊,請參閱 C# 語言規格中的 Unsafe 程式碼。 語言規格是 C# 語法及用法的限定來源。

另請參閱