Base di conoscenzaCentro esami
ITItaliano
Scegli la lingua13

CKTIS / C#

fixed: riferimento pratico

fixed: riferimento pratico: fixed blocca memoria gestita ed espone un puntatore stabile in un ambito limitato.

Versione: C# language; verified against C# 14 reference

Sintassi

fixed /* grammar-specific form */

fixed blocca memoria gestita ed espone un puntatore stabile in un ambito limitato.

Usalo solo per interop breve o per un algoritmo unsafe che richiede un indirizzo.

Un pinning lungo frammenta l’heap e il puntatore non deve uscire dal blocco.

Uno span vuoto può produrre un puntatore null; il codice richiede unsafe e un tipo elemento valido.

Il programma completo usa realmente fixed; lo stdout esatto atteso è 7.

Esempi

using System;
using System.Buffers;
using System.Collections.Concurrent;
using System.Collections.Frozen;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.Json;
using System.Text.Json.Nodes;
using System.Text.Json.Serialization;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Channels;
using System.Threading.Tasks;
using Number = System.Int32;

unsafe { var values = new[] { 7 }; fixed (int* pointer = values) Console.WriteLine(*pointer); }

Risultato

7

Il programma completo usa realmente `fixed`; lo stdout esatto atteso è `7`.

Fonti