Repository navigation
ZH TW CSharp Keyword fixed
Codex edited this page Oct 11, 2026
·
2 revisions
Українська · Русский · English · Deutsch · Français · Italiano · Español · 繁體中文 · 日本語 · 한국어
在區塊的持續時間內,它使託管資料保持不動,以便透過指標進行工作;固定緩衝區——結構體欄位的單獨聲明。
請將此範例另存為 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。
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); }
}
}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]);
}
}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學習。
ClassicUO — Bad Newbie & C# Scripts IDE