unsafe (C# Reference)

关键字 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 编译器选项。 公共语言运行时无法验证不安全的代码。

示例:

// 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# 语法和用法的明确来源。

另请参阅