Base de conocimientosCentro de exámenes
ESEspañol
Elegir idioma13

CKTIS / C#

pattern matching: referencia práctica

pattern matching: referencia práctica: Los patrones C# prueban tipo, valor y estructura y pueden enlazar variables.

Versión: C# language and .NET 10 reference runtime

Sintaxis

// patterns

Los patrones C# prueban tipo, valor y estructura y pueden enlazar variables.

Usa una switch expression para mapear exhaustivamente los casos.

El orden de los brazos importa; un patrón amplio anterior puede ocultar los posteriores.

null no coincide con un patrón de tipo normal; si una switch expression no exhaustiva carece de un brazo aplicable, puede lanzar SwitchExpressionException.

El programa completo usa realmente pattern matching; su stdout esperado exacto es positive:7.

Ejemplos

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;

object value = 7; var text = value switch { int number and > 0 => $"positive:{number}", null => "null", _ => "other" }; Console.WriteLine(text);

Resultado

positive:7

El programa completo usa realmente `pattern matching`; su stdout esperado exacto es `positive:7`.

Fuentes