Skip to content

RU CSharp Keyword fixed

Codex edited this page Oct 11, 2026 · 2 revisions

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

C#: fixed

Справочник C# · Практическое руководство

На время блока удерживает managed-данные неподвижными для работы через указатель; fixed buffer – отдельное объявление поля структуры.

Простой пример (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. Для managed-данных обычно проще работать через 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 Learn.

Clone this wiki locally