Skip to content

ZH TW CSharp Keyword fixed

Codex edited this page Oct 11, 2026 · 2 revisions

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

C#: fixed

使用手冊C# · 實用指南

在區塊的持續時間內,它使託管資料保持不動,以便透過指標進行工作;固定緩衝區——結構體欄位的單獨聲明。

簡單範例 (Example.cs)

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

Example.cs:

// PROJECT-EXAMPLE
int[] values = [3];
unsafe
{
    fixed (int* pointer = values) *pointer = 7;
}
System.Console.WriteLine(values[0]);

請在專案中啟用 <AllowUnsafeBlocks>true</AllowUnsafeBlocks>。指標僅在所示範圍內有效。

結果:

7

句法

fixed (Type* pointer = managedValue) { ... }

在.csproj中,設定true。對於託管數據,通常更容易在沒有原始指標的情況下使用 Span。

例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)
    {
        string text = "ore";
        unsafe { fixed (char* pointer = text) Console.WriteLine(*pointer); }
    }
}

例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)
    {
        int[] values = [2, 4, 6];
        unsafe { fixed (int* pointer = values) { pointer[1] = 9; Console.WriteLine(*(pointer + 1)); Console.WriteLine(sizeof(long)); } }
        Console.WriteLine(values[1]);
    }
}

範例3

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)
    {
        unsafe { Packet packet = default; packet.Bytes[0] = 7; Console.WriteLine(packet.Bytes[0]); }
    }
}
public unsafe struct Packet { public fixed byte Bytes[4]; }

官方來源:Microsoft學習。

Clone this wiki locally