前置知识:lambda表达式,枚举与Switch(传统语法)C# & Unity 面向对象补全计划 之 匿名函数与Lambda表达式-CSDN博客
C# 8.0引入了 switch 表达式,是一个语法糖(类的属性get set就是一种语法糖)
基本规则:
var result = expression switch {
pattern1 => result1,
pattern2 => result2,
...
_ => defaultResult
};
expression
是你要检查的值pattern1
,pattern2
, … 是你要匹配的模式result1
,result2
, … 是对应模式匹配成功时的结果_
是默认模式,相当于传统 switch 语句中的default
实战演示:
传统枚举和Switch
// See https://aka.ms/new-console-template for more information
Age myAge = Age.young;
SelectAge(myAge);
void SelectAge(Age age)
{
switch (age)
{
case Age.kid:
Console.WriteLine("小孩");
break;
case Age.young:
Console.WriteLine("年轻");
break;
case Age.middleAge:
Console.WriteLine("中年");
break;
case Age.old:
Console.WriteLine("老年");
break;
default:break;
}
}
public enum Age:int{
kid,
young,
middleAge,
old
}
都什么年代了还在用传统Switch!?
// See https://aka.ms/new-console-template for more information
Age myAge = Age.young;
SelectAge(myAge);
void SelectAge(Age age)
{
var result = age switch {
Age.kid => "小孩",
Age.young => "年轻",
Age.middleAge => "中年",
Age.old => "老年",
_ => null
};
Console.WriteLine(result);
}
public enum Age:int{
kid,
young,
middleAge,
old
}
可以看到在这个语法糖之中,返回值会被更加轻松简单地运用