[英]Expressions inside C# 8 switch
I'd like to be able to call a method/local function from within the new C# switch expression pattern matching.我希望能够从新的 C# 开关表达式模式匹配中调用方法/本地 function。
Here's an example I've got:这是我得到的一个例子:
string result = value switch
{
IsFizz(value) => "Fizz",
IsBuzz(value) => "Buzz",
(IsFizz(value) && IsBuzz(value)) => "FizzBuzz",
_ => value.ToString()
};
However I get the follow errors:但是我收到以下错误:
A single-element deconstruct pattern requires some other syntax for disambiguation.单元素解构模式需要一些其他语法来消除歧义。 It is recommended to add a discard designator '_' after the close paren ')'.建议在右括号 ')' 之后添加丢弃指示符 '_'。
Sytnax error, '=>' expected语法错误,预期为“=>”
Invalid expression term '&&'无效的表达式术语“&&”
Is it not possible to use new the switches in this manner?不能以这种方式使用新的开关吗?
Yes, but in the when
clause:是的,但是在when
子句中:
string result = value switch
{
_ when IsFizz(value) => "Fizz",
_ when IsBuzz(value) => "Buzz",
_ when (IsFizz(value) && IsBuzz(value)) => "FizzBuzz",
_ => value.ToString()
};
(shouldn't the FizzBuzz
test come first?) (不应该先进行FizzBuzz
测试吗?)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.