Baza wiedzyCentrum egzaminacyjne
PLPolski
Wybierz język13

CKTIS / C#

scope and lifetime: odniesienie praktyczne

scope and lifetime: odniesienie praktyczne: Zakres określa widoczność nazwy, a lifetime czas ważności wartości lub zasobu.

Wersja: C# language and .NET 10 reference runtime

Składnia

// scope lifetime

Zakres określa widoczność nazwy, a lifetime czas ważności wartości lub zasobu.

Ograniczaj zakres zmiennych i własność zasobów do najmniejszego potrzebnego obszaru.

Closure może wydłużyć życie obiektu i przechwycić zmienną, nie migawkę wartości.

Ref/span nie może przeżyć pamięci bazowej ani uciec poza bezpieczny zakres.

Kompletny program rzeczywiście używa scope and lifetime; oczekiwany stdout to dokładnie 5.

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 outer = 2; { var inner = 3; Console.WriteLine(outer + inner); }

Wynik

5

Kompletny program rzeczywiście używa `scope and lifetime`; oczekiwany stdout to dokładnie `5`.

Źródła