unsafe(C# 参考)unsafe (C# Reference)

unsafe 关键字表示不安全上下文,该上下文是任何涉及指针的操作所必需的。The unsafe keyword denotes an unsafe context, which is required for any operation involving pointers. 有关详细信息,请参阅不安全代码和指针For more information, see Unsafe Code and Pointers.

可在类型或成员的声明中使用 unsafe 修饰符。You can use the unsafe modifier in the declaration of a type or a member. 因此,类型或成员的整个正文范围均被视为不安全上下文。The entire textual extent of the type or member is therefore considered an unsafe context. 以下面使用 unsafe 修饰符声明的方法为例:For example, the following is a method declared with the unsafe modifier:

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

不安全上下文的范围从参数列表扩展到方法的结尾,因此也可在以下参数列表中使用指针:The scope of the unsafe context extends from the parameter list to the end of the method, so pointers can also be used in the parameter list:

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

还可以使用不安全块从而能够使用该块内的不安全代码。You can also use an unsafe block to enable the use of an unsafe code inside this block. 例如:For example:

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

要编译不安全代码,必须指定 -unsafe 编译器选项。To compile unsafe code, you must specify the -unsafe compiler option. 不能通过公共语言运行时验证不安全代码。Unsafe code is not verifiable by the common language runtime.

示例Example

// 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# language specification

有关详细信息,请参阅 C# 语言规范中的不安全代码For more information, see Unsafe code in the C# Language Specification. 该语言规范是 C# 语法和用法的权威资料。The language specification is the definitive source for C# syntax and usage.

请参阅See also