不安全代码和指针(C# 编程指南)Unsafe code and pointers (C# Programming Guide)

为了保持类型安全性,默认情况下,C# 不支持指针算法。To maintain type safety and security, C# does not support pointer arithmetic, by default. 但是,通过使用 unsafe 关键字,可以定义可在其中使用指针的不安全上下文。However, by using the unsafe keyword, you can define an unsafe context in which pointers can be used. 若要详细了解指针,请参阅指针类型For more information about pointers, see Pointer types.

备注

在公共语言运行时 (CLR) 中,不安全代码是指无法验证的代码。In the common language runtime (CLR), unsafe code is referred to as unverifiable code. C# 中的不安全代码不一定是危险的;只是 CLR 无法验证该代码的安全性。Unsafe code in C# is not necessarily dangerous; it is just code whose safety cannot be verified by the CLR. 因此,CLR 将仅执行完全信任的程序集中的不安全代码。The CLR will therefore only execute unsafe code if it is in a fully trusted assembly. 如果你使用不安全代码,你应该负责确保代码不会引发安全风险或指针错误。If you use unsafe code, it is your responsibility to ensure that your code does not introduce security risks or pointer errors.

不安全代码概述Unsafe code overview

不安全代码具有以下属性:Unsafe code has the following properties:

  • 可将方法、类型和代码块定义为不安全。Methods, types, and code blocks can be defined as unsafe.

  • 在某些情况下,通过移除数组绑定检查,不安全代码可提高应用程序的性能。In some cases, unsafe code may increase an application's performance by removing array bounds checks.

  • 调用需要指针的本机函数时,需使用不安全代码。Unsafe code is required when you call native functions that require pointers.

  • 使用不安全代码将引发安全风险和稳定性风险。Using unsafe code introduces security and stability risks.

  • 必须使用 -unsafe 编译器选项来编译包含不安全块的代码。The code that contains unsafe blocks must be compiled with the -unsafe compiler option.

有关详细信息,请参见:For more information, see:

C# 语言规范C# language specification

有关详细信息,请参阅 C# 语言规范中的不安全代码主题。For more information, see the Unsafe code topic of the C# language specification.

请参阅See also