unsafe 关键字表示不安全上下文,该上下文是任何涉及指针的操作所必需的。
可以在类型或成员的声明中使用 unsafe 修饰符。因此,类型或成员的整个正文范围均被视为不安全上下文。例如,以下是用 unsafe 修饰符声明的方法:
// cs_unsafe_keyword.cs // compile with: /unsafe using System; 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); } }
输出
25