本文介绍了空条件和空coalescing运算符*与*普通布尔表示法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

示例1:

var ca = p.GetCustomAttribute<ConnectorAttribute>();
return ca?.Point.IsEqual(cp) ?? false;

示例2:

var ca = p.GetCustomAttribute<ConnectorAttribute>();
return (null != ca) && ca.Point.IsEqual(cp);

问题:

  • 两个示例返回相同的结果吗?
  • 哪个表现更好?
  • 是否有关于线程安全性的担忧?

没人提到,但是标题有一些错误,我已经纠正了.

Nobody mention but the title had some error, I've corrected it.

根据注释,那些代码是相同的".对我来说,它仍然不像它看起来那么琐碎.

Edit 2: According the comments, 'those code are the same'. For me it is still not as trivial as it seams to be.

此处的答案表明,示例1的第一部分.创建一个Nullable<bool>类型.是否由于空值运算符而对其进行了优化?

The answer here tells that the first part of example 1. creates a Nullable<bool> type. Is it optimized because of the null-coalescing operator?

推荐答案

第一个问题的答案:是的.

Answer to your first question: Yes.

对第二个问题的简短回答:没有,您应该根据更具可读性的内容进行选择.

Short answer to your second question: None, you should choose based on which is more readable.

回答第三个问题:如果您希望整个表达式一次性运行",因此不会受到并发问题的影响,那么否,空值促销运算符不能保证如答案中所述 Stackoverflow问题.在两个示例中,您实际上都将面临相同的并发挑战.

Answer to your third question: if you expect the whole expression to run "in one shot" and therefore not be subject to concurrency issues, then no, the null-coalescing operator does not guarantee that as explained in the answer of this Stackoverflow question.In both your examples you would actually face the same concurrency challenges.

查看 Microsoft' ??' doc ,所提及的只是操作员的目的和功能:

Looking in the Microsoft '??' doc, all is mentioned is the operator purpose and function:

因此,null-coalescing运算符使您可以编写更简洁的代码,否则该代码将要求您两次编写有问题的操作数(如第二个示例中所示).

Hence, the null-coalescing operator makes you write cleaner code that would otherwise require you to write the operand in question twice (as in your 2nd example).

使用空coalescing运算符与效用比性能更相关,因为解释了.确实,两者的表现完全相同.

Usage of the null-coalescing operator is more related to utility than performance, as explained is the accepted answer of a similar Stackoverflow question. Indeed, both perform quite the same.

作为同一个答案的一部分,有趣的是,null-coalescing运算符的执行速度似乎稍快一些,但差异很小,可以忽略不计.

Interesting to notice, as part of the same answer, the null-coalescing operator seems to perform slightly faster, but the difference is so little that could be ignored.

这篇关于空条件和空coalescing运算符*与*普通布尔表示法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-16 17:42