简体   繁体   English

新的 C# 8.0 开关表达式的运算符优先级是什么?

[英]What is the operator precedence for the new C# 8.0 switch expressions?

I just upgraded my current project to the newly released .NET Standard 2.1 and C# 8.0, and decided to convert some large switch statements into the new, much more compact expression syntax .我刚刚将我当前的项目升级到新发布的 .NET Standard 2.1 和 C# 8.0,并决定将一些大型switch语句转换为新的、更紧凑的表达式语法

Since the returned values are further used in some computations, I was wondering how the new switch expressions behave when the input variable is next to an operator.由于返回值在某些计算中被进一步使用,我想知道当输入变量靠近运算符时新的switch表达式的行为。

Take the following example for string concatenation:以以下示例进行字符串连接:

string input = Console.ReadLine();
string output = "Letter: " + input switch
{
    "1" => "a",
    "2" => "b",
    _ => "else"
};
Console.WriteLine(output);

I guess that the switch binds very strongly to the input variable, and thus is evaluated first.我猜这个switchinput变量的绑定非常紧密,因此首先被评估。 And indeed, this prints Letter: a , when I type 1 .事实上,当我输入1时,它会打印Letter: a

But my question now is: Does this behavior apply to any operator?但我现在的问题是:这种行为是否适用于任何运营商?

From my experiments, I was not able to identify a condition where the above hypothesis does not hold, but that obviously does not mean that there isn't a case that I have missed.从我的实验中,我无法确定上述假设不成立的情况,但这显然并不意味着我没有错过任何情况。 The docs also don't seem to mention operator precedence in context of switch expressions.文档似乎也没有在switch表达式的上下文中提及运算符优先级。 Or do I have some deeper misunderstanding here?还是我在这里有一些更深的误解?

The Roslyn source suggests that indeed switch expressions have fairly high precedence, but there are some things with higher precedence such as ranges, unary operators, and casts. Roslyn 的资料表明switch表达式确实具有相当高的优先级,但有些东西具有更高的优先级,例如范围、一元运算符和强制转换。 See here and here in the Roslyn source.请参阅 Roslyn 源中的此处此处

Example code that demonstrates higher precedence of SyntaxKind.LogicalNotExpression ( Precende.Unary ):演示SyntaxKind.LogicalNotExpression ( Precende.Unary ) 更高优先级的示例代码:

var foo = false;
var bar = !foo switch {
    true => "true",
    false => "false"
};
Console.WriteLine(bar); // writes "true"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM