如果左操作数的?运营商不为空,不正确的操作得到评估? [英] If the left operand to the ?? operator is not null, does the right operand get evaluated?

查看:165
本文介绍了如果左操作数的?运营商不为空,不正确的操作得到评估?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我期待在使用 ?? 操作符(空合并运算符)在C#中。但在MSDN的文档是有限的。

I'm looking at using the ?? operator (null-coalescing operator) in C#. But the documentation at MSDN is limited.

我的问题:如果左边的操作数不为空,不正确的操作数不断得到评估

My question: If the left-hand operand is not null, does the right-hand operand ever get evaluated?

推荐答案

与以往一样,C#的规范去这样的事情最好的地方。

As ever, the C# specification is the best place to go for this sort of thing.

C#5规范(重点煤矿)第7.13:

From section 7.13 of the C# 5 specification (emphasis mine):

一个空合并的形式 A的前pression? b 要求 A 是一个可空类型或引用类型。如果 A A 就是非空,结果? b A ;否则,其结果是 B 的操作先计算 B A 为空。

A null coalescing expression of the form a ?? b requires a to be of a nullable type or reference type. If a is non-null, the result of a ?? b is a; otherwise, the result is b. The operation evaluates b only if a is null.

有在任何转换都围绕着更多的详细信息,以及准确的行为,但是这是给你的问题​​的主要观点。另外值得一提的是,空合并运算符是右结合的,所以 A? B 12 ç被评为 A? (二?? C) ...这意味着它仅评估 C 如果的两个 B 是空的。

There are more details around when any conversions are performed, and the exact behaviour, but that's the main point given your question. It's also worth noting that the null-coalescing operator is right-associative, so a ?? b ?? c is evaluated as a ?? (b ?? c)... which means it will only evaluate c if both a and b are null.

这篇关于如果左操作数的?运营商不为空,不正确的操作得到评估?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆