Baza wiedzyCentrum egzaminacyjne
PLPolski
Wybierz język13

CKTIS / C#

ref: odniesienie praktyczne

ref: odniesienie praktyczne: ref przekazuje lub zwraca alias do istniejącej lokalizacji zamiast kopii.

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

Składnia

ref /* grammar-specific form */

ref przekazuje lub zwraca alias do istniejącej lokalizacji zamiast kopii.

Stosuj do wydajnej mutacji dużych struct i API spanowych z kontrolowanym lifetime.

Alias może naruszyć invariant i utrudnia analizę; nie może przeżyć referenta.

Ref local musi być zainicjalizowany referencją; ref return podlega escape analysis.

Kompletny program rzeczywiście używa ref; 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;

var value = 2; ref var alias = ref value; alias = 7; Console.WriteLine(value);

Wynik

7

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

Źródła