简体   繁体   English

C#中的运算符优先级和关联性

[英]Operator precedence and associativity in C#

I've two lines of coding as below 我有两行编码,如下所示

int? i = 1;
int j = i ?? 2 +1;

now "j is 1"

int? i = 1;
int j = (i ?? 2) +1;

now "j is 2"

Could you explain how? 你能解释一下吗?

Sure - it's simple a matter of precedence. 当然-这只是一个优先事项。 The (Microsoft) C# specification lists operator precedence in section 7.3.1 (in the C# 4 and C# 5 specifications, anyway; it's 7.2.1 in the C# 3 spec), although that's only really an informative table - it's really governed by the grammar. (Microsoft)C#规范在7.3.1节中列出了运算符的优先级(无论如何,在C#4和C#5规范中;在C#3规范中为7.2.1),尽管这实际上只是一个信息量大的表-它实际上受语法。

Anyway, the null-coalescing operator ( ?? ) has lower precedence than the binary addition operator ( + ) so your first code is equivalent to: 无论如何,空值运算符( ?? )的优先级低于二进制加法运算符( + )的优先级,因此您的第一个代码等效于:

int? i = 1;
int j = i ?? (2 + 1);

As the value of i is non-null, the right hand operand of the null-coalescing operator isn't even evaluated - the result of i ?? (2 + 1) 由于i的值不为null,因此甚至不评估null运算符的右操作数i ?? (2 + 1)的结果i ?? (2 + 1) i ?? (2 + 1) is just 1. i ?? (2 + 1)只是1。

Compare that with your second example, where the null-coalescing operator expression again evaluates to 1, but then 1 is added to the result of that. 将其与您的第二个示例进行比较,在该示例中,null-coalescing运算符表达式再次求值为1,然后将1加到该结果中。 It's effectively: 有效的是:

int tmp = i ?? 2; // tmp is now 1
int j = tmp + 1;  // j is 2

Associativity is irrelevant here, has it only controls the ordering/grouping when an operand occurs between two operators with the same precedence. 关联在这里无关紧要,只有在操作数出现在两个具有相同优先级的运算符之间时,它才控制顺序/分组。

Maybe you will understand it better without the use of the ?? 也许您不使用??会更好地理解它 operator 算子

Scenario 1: 方案1:

int? i = 1;
int j;
if (i != null)
{
    //i is not null so this is hit
    j = i;
}
else
    j = 2 + 1;
}

So j = 1 所以j = 1

Scenario 2: 方案2:

int? i = 1;
int j;
if (i != null)
{
    //i is not null so this is hit
    j = i;
}
else
    j = 2;
}

So j = 1 所以j = 1

//No matter the result of the above if, 1 is always added.
j = j + 1;

So j = 2 所以j = 2

int? i = 1;
int j = i ?? 2 + 1; //If I is null make j = to 3

Now j is 1 现在j是1

int? i = 1;
int j = (i ?? 2) + 1;  //If I is null make j = 2 else make j = to 0 and then add 1 

Now j is 2 现在j是2

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

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