CKTIS / C#
pattern matching: riferimento pratico
pattern matching: riferimento pratico: I pattern C# verificano tipo, valore e struttura e possono associare variabili.
Versione: C# language and .NET 10 reference runtime
Sintassi
// patternsI pattern C# verificano tipo, valore e struttura e possono associare variabili.
Usa una switch expression per mappare esaustivamente i casi.
L’ordine dei rami conta; un pattern ampio precedente può oscurare i successivi.
null non corrisponde a un normale pattern di tipo; un caso mancante può generare un’eccezione.
Il programma completo usa realmente pattern matching; lo stdout esatto atteso è positive:7.
Esempi
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);
Risultato
positive:7
Il programma completo usa realmente `pattern matching`; lo stdout esatto atteso è `positive:7`.