Skip to content

IT CSharp Keyword fixed

Codex edited this page Oct 11, 2026 · 2 revisions

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

C#: fixed

Manuale C# · Guida pratica

Per tutta la durata del blocco mantiene i dati gestiti immobili per la lavorazione tramite puntatore; buffer fisso: una dichiarazione separata di un campo di struttura.

Esempio semplice (Example.cs)

Salvare questo esempio separatamente come Example.cs. Eseguirlo indipendentemente dagli altri esempi di questa pagina.

Example.cs:

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

Abilitare <AllowUnsafeBlocks>true</AllowUnsafeBlocks> nel progetto. Il puntatore è valido solo nell’ambito mostrato.

Risultato:

7

Sintassi

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

In .csproj, imposta true. Per i dati gestiti, in genere è più semplice utilizzare Span senza puntatori non elaborati.

Esempio 1: forma base

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); }
    }
}

Esempio 2: un'altra forma pratica

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]);
    }
}

Esempio 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]; }

Fonte ufficiale: Microsoft Impara.

Clone this wiki locally