static void SwitchStatement(object item)
{
switch (item)
{
case null:
case 42:
Console.WriteLine("it's a const pattern");
break;
case int i:
Console.WriteLine($"it's a type pattern with int: {i}");
break;
case string s:
Console.WriteLine($"it's a type pattern with string: {s}");
break;
case Person p when p.FirstName == "Katharina":
Console.WriteLine($"type pattern match with Person and " +
$"when clause: {p}");
break;
case Person p:
Console.WriteLine($"type pattern match with Person: {p}");
break;
case var every:
Console.WriteLine($"var pattern match: {every?.GetType().Name}");
break;
default:
}
}
Pattern Matching with the switch Statement
最新推荐文章于 2023-10-07 09:43:36 发布
本文深入探讨了如何利用switch语句在编程中实现高效且灵活的模式匹配,涵盖了不同类型的匹配策略,并提供了实例来说明其在实际问题解决中的应用。
9332

被折叠的 条评论
为什么被折叠?



