Base de conhecimentoCentro de Exames
PT · PTPortuguês (Portugal)
Escolher idioma13

CKTIS / C#

System.Span: referência prática

System.Span: referência prática: Span<T> é uma vista mutável, limitada à stack, de uma região contígua de memória.

Versão: .NET API; verified against .NET 10 reference surface

Sintaxe

System.Span /* select a documented member or constructor */

Span é uma vista mutável, limitada à stack, de uma região contígua de memória.

Usa-o em caminhos síncronos críticos para trabalhar sem copiar.

Como ref struct não pode escapar para a heap nem atravessar await ou yield.

Slice e a indexação validam limites; stackalloc tem um orçamento de stack limitado.

O programa completo usa realmente System.Span; o stdout exato esperado é 3,2,1.

Exemplos

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;

Span<int> span = stackalloc[] { 1, 2, 3 };
span.Reverse();
Console.WriteLine(string.Join(",", span.ToArray()));

Resultado

3,2,1

O programa completo usa realmente `System.Span`; o stdout exato esperado é `3,2,1`.

Fontes