您好,欢迎访问一九零五行业门户网

如何在 C# 8.0 中编写新的 Switch 表达式?

switch表达式在表达式上下文中提供了类似switch的语义。
switch是一个选择语句,根据与匹配表达式的模式匹配,从候选列表中选择一个单独的switch部分来执行。
如果一个单独的表达式需要与三个或更多条件进行测试,通常使用switch语句作为if-else结构的替代方案。
示例新的switch写法
var message = c switch{ fruits.red => "the fruits is red", fruits.green => "the fruits is green", fruits.blue => "the fruits is blue"};
示例 1class program{ public enum fruits { red, green, blue } public static void main(){ fruits c = (fruits)(new random()).next(0, 3); switch (c){ case fruits.red: console.writeline("the fruits is red"); break; case fruits.green: console.writeline("the fruits is green"); break; case fruits.blue: console.writeline("the fruits is blue"); break; default: console.writeline("the fruits is unknown."); break; } var message = c switch{ fruits.red => "the fruits is red", fruits.green => "the fruits is green", fruits.blue => "the fruits is blue" }; system.console.writeline(message); console.readline(); }}
输出the fruits is greenthe fruits is green
以上就是如何在 c# 8.0 中编写新的 switch 表达式?的详细内容。
其它类似信息

推荐信息