CKTIS / C#
pattern matching: практическа справка
pattern matching: практическа справка: Шаблоните C# проверяват тип, стойност и структура и могат да свързват променливи.
Версия: C# language and .NET 10 reference runtime
Синтаксис
// patternsШаблоните C# проверяват тип, стойност и структура и могат да свързват променливи.
Използвайте switch expression за изчерпателно съпоставяне на случаите.
Редът на рамената има значение; по-ранен широк шаблон може да скрие следващи.
null не съвпада с обикновен шаблон за тип; ако неизчерпателен switch expression няма приложимо рамо, може да хвърли SwitchExpressionException.
Пълната програма действително използва pattern matching; точният очакван stdout е positive:7.
Примери
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);
Резултат
positive:7
Пълната програма действително използва `pattern matching`; точният очакван stdout е `positive:7`.