Skip to content

ZH TW CSharp Keyword safe

Codex edited this page Oct 11, 2026 · 2 revisions

Українська · Русский · English · Deutsch · Français · Italiano · Español · 繁體中文 · 日本語 · 한국어

C#: safe

使用手冊C# · 實用指南

更新的記憶體安全模型的預覽修飾符:作者明確地將聲明標記為不需要呼叫者的不安全上下文。

簡單範例 (Example.cs)

請將此範例另存為 Example.cs,並與本頁其他範例分開執行。

Example.cs:

// PROJECT-EXAMPLE
class ManagedValue { public int Count { get; set; } }

此簡短範例使用 C# 14,並未實作此處不支援的預覽語法 safe。

句法

public static safe extern int Method();

這是 C# 15 / .NET 11 的預覽。官方規則要求 LangVersion=預覽並為其應用程式單獨啟用更新的記憶體安全規則。目前的C#14不支持這些聲明。

**狀態:預覽;目前配置 C# 14 / .NET 10 不支援這些範例。 **

例1:基本形式

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.IO;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;

public static class Program
{
    public static async Task Main(string[] args)
    {
        Console.WriteLine(Native.GetCurrentProcessId());
    }
}
public static class Native { [DllImport("kernel32.dll")] public static safe extern uint GetCurrentProcessId(); }

例2:另一種實用形式

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.IO;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;

public static class Program
{
    public static async Task Main(string[] args)
    {
        Union value = new() { Integer = 1065353216 };
        Console.WriteLine(value.Real);
    }
}
[StructLayout(LayoutKind.Explicit)] public struct Union { [FieldOffset(0)] public safe int Integer; [FieldOffset(0)] public safe float Real; }

官方來源:Microsoft學習。

Clone this wiki locally