不安全的程式碼和指標 (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.

注意

在 Common Language Runtime (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