Baza wiedzyCentrum egzaminacyjne
PLPolski
Wybierz język13

CKTIS / C#

fixed: odniesienie praktyczne

fixed: odniesienie praktyczne: fixed przypina zarządzaną pamięć i udostępnia stabilny wskaźnik w ograniczonym zakresie.

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

Składnia

fixed /* grammar-specific form */

fixed przypina zarządzaną pamięć i udostępnia stabilny wskaźnik w ograniczonym zakresie.

Stosuj tylko do krótkiego interopu lub unsafe algorytmu wymagającego adresu.

Długie pinning fragmentuje stertę; wskaźnik nie może uciec poza blok.

Pusty span może dać null pointer; kod wymaga unsafe i poprawnego typu elementu.

Kompletny program rzeczywiście używa fixed; oczekiwany stdout to dokładnie 7.

Przykłady

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

Wynik

7

Kompletny program rzeczywiście używa `fixed`; oczekiwany stdout to dokładnie `7`.

Źródła