unsafe 关键字表示不安全上下文,该上下文是任何涉及指针的操作所必需的。有关更多信息,请参见
不安全代码和指针(C# 编程指南)。
可以在类型或成员的声明中使用 unsafe 修饰符。因此,类型或成员的整个正文范围均被视为不安全上下文。例如,以下是用 unsafe 修饰符声明的方法:
不安全上下文的范围从参数列表扩展到方法的结尾,因此指针在以下参数列表中也可以使用:
还可以使用不安全块从而能够使用该块内的不安全代码。例如:
若要编译不安全代码,必须指定 /unsafe 编译器选项。无法通过公共语言运行库验证不安全代码。
注意 |
---|
无法修改在 fixed 语句中初始化的指针。 |
在不安全模式中,可以在堆栈上分配内存。堆栈不受垃圾回收的制约,因此不需要被锁定。有关更多信息,请参见 stackalloc。