赞
踩
首先检查value
的类型,然后根据类型输出相应的消息
public void ShowMessage(object value)
{
switch (value)
{
case int i: Console.WriteLine($"value is int:{i}"); break;
case long l: Console.WriteLine($"value is long:{l}"); break;
case bool b: Console.WriteLine($"value is bool:{b}"); break;
case string s: Console.WriteLine($"value is string:{s}"); break;
default: Console.WriteLine($"value is object"); break;
}
}
类型模式可以理解为在声明模式中使用了弃元:
public void ShowMessage(object value)
{
switch (value)
{
case int: Console.WriteLine($"value is int"); break;
case long: Console.WriteLine($"value is long"); break;
case bool: Console.WriteLine($"value is bool"); break;
case string: Console.WriteLine($"value is string"); break;
default: Console.WriteLine($"value is object"); break;
}
}
常量模式可以理解为原来C#6.0及之前的用法:
switch (score)
{
case 10:
case 9:
Console.WriteLine("优秀");
break;
case 8:
Console.WriteLine("良好");
break;
case 7:
case 6:
Console.WriteLine("及格");
break;
default:
Console.WriteLine("不及格");
break;
}
switch(score)
{
case >=80:
Console.WriteLine("excellent");
break;
case >=60:
Console.WriteLine("good");
break;
default:
Console.WriteLine("poor");
break;
}
switch(value)
{
case 0:
Console.WriteLine("value is 0");
break;
case not 0 and(100 or - 100):
Console.WriteLine("abs(value)==100");
break;
case not 0 and( > 0 and < 100):
Console.WriteLine("value is positive and less than 100");
break;
case not 0 and > 0:
Console.WriteLine("value is positive and greater than 100");
break;
case <-100 or( < 0 and > -100):
Console.WriteLine("value is negative and not equals -100");
break;
}
switch(time)
{
case {
Year: 2020 or 2021,
Month: <= 6,
Day: 1
}
t:
Console.WriteLine($ "the first day of every month in the first half of 2020 and 2021");
break;
case {
Year: not 2022
}:
Console.WriteLine($ "not 2022");
break;
case {
DayOfWeek: not DayOfWeek.Sunday and not DayOfWeek.Saturday
}:
Console.WriteLine($ "recursion");
break;
}
位置模式采用解构的特性来说明指定的模式是否匹配:
public record Point2D(int X, int Y); //记录可以解构
static void Print(Point2D point)
{
switch(point)
{
case( > 0, > 0):
Console.WriteLine("first quadrant");
break;
case( < 0, > 0):
Console.WriteLine("second quadrant");
break;
case( < 0, < 0):
Console.WriteLine("third quadrant");
break;
case( > 0, < 0):
Console.WriteLine("fourth quadrant");
break;
default:
Console.WriteLine("coordinate axis");
break;
}
}
Var模式往往和属性模式和位置模式结合,用于提取属性变量值:
switch(point)
{
case(var x,
var y,
var z):
Console.WriteLine($ "3D point:({x},{y},{z})");
break; //在位置模式中使用
case Point2D
{
X: var x, Y: var y
}:
Console.WriteLine($ "2D point:({x},{y})");
break; //在属性模式中使用
default:
Console.WriteLine("others");
break;
}
弃元模式在switch语句中用的不多,但是在switch表达式中使用的多:
var result = score
switch
{ >= 80 => "excellent", >= 60 => "good",
_ => "poor" //弃元在switch表达式中就相当于default
};
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。