Baza wiedzyCentrum egzaminacyjne
PLPolski
Wybierz język13

CKTIS / C#

when: odniesienie praktyczne

when: odniesienie praktyczne: when dodaje filtr do catch albo guard do wzorca switch.

Wersja: C# language; verified against C# 14 reference

Składnia

when /* grammar-specific form */

when dodaje filtr do catch albo guard do wzorca switch.

Stosuj do zawężenia przypadku bez przechwytywania niepasującego wyjątku.

Filtr powinien być bezpieczny i bez skutków; jego false kontynuuje wyszukiwanie handlera.

Wyjątek z filtra jest traktowany jak false w obsłudze wyjątków.

Kompletny program rzeczywiście używa when; oczekiwany stdout to dokładnie filtered.

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;

try { throw new ArgumentException("x"); } catch (ArgumentException error) when (error.Message.StartsWith("x")) { Console.WriteLine("filtered"); }

Wynik

filtered

Kompletny program rzeczywiście używa `when`; oczekiwany stdout to dokładnie `filtered`.

Źródła