共用方式為


unsafe (C# 參考)

關鍵詞 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
{
    // 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# 語言規格中的不安全程式碼。 語言規格是 C# 語法和使用方式的最終來源。

另請參閱