简体   繁体   English

检查null,== null vs!= null

[英]Checking for null, == null vs != null

Is there a recommended way (according to .net Framework guidelines) of checking for null, example: 是否有一种检查null的推荐方法(根据.net框架指南),例如:

if (value == null)
{//code1}
else
{//code2}

or 要么

if (value != null)
{//code2}
else
{//code1}

Or the both codes has same performance? 或者两个代码具有相同的性能?

Both options will perform identically. 两个选项的表现都相同。

You should use whichever one makes sense semantically, or whichever one results in cleaner code. 你应该使用语义上有意义的,或者使用更清晰的代码。
For example, if the non-null action is shorter, it makes sense to put that block first, so that the else is close to the if . 例如,如果非null操作较短,则将该块放在第一位是有意义的,以便else接近if

There is no performance difference, so you should strive for improved readability. 没有性能差异,因此您应该努力提高可读性。

For example, it is often a good idea to put the more "regular" path in the if branch, and put the "exceptional" one in the else branch. 例如,将更多“常规”路径放在if分支中,并将“例外”路径放在else分支中通常是个好主意。

There's no difference in performance. 性能没有区别。 I personally put the more common case on top and the less common case in the else branch but that's just preference. 我个人把更常见的情况放在最上面,而在else分支中则不常见,但这只是偏好。 This makes it easier for me to see the more common scenario. 这使我更容易看到更常见的场景。

There is no performance difference. 没有性能差异。 Use them as per your need(readability/usability perspective). 根据您的需要使用它们(可读性/可用性视角)。 Most appropriate/used block goes in if and the optional/secondary block goes in else . 最合适/使用的块进入if并且可选/辅助块进入else

both are same.. for readability you can put the block of code in IF which gives the result as true. 两者都是相同的...为了便于阅读,您可以将代码块放在IF中,结果为true。 In this case IF(value != null) is better readable and obvious :) 在这种情况下,IF(值!= null)更易读,更明显:)

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

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