if(null == this)有什么区别?Somevariable)和if(this).Somevariable ==

本文关键字:Somevariable if this null 什么 区别 | 更新日期: 2023-09-27 18:05:30

愚蠢的问题我明白了,但是这两句话有什么区别

if( null == this.someVariable)
{
 //do something
}
and 
if( this.someVariable == null )
{
//do something.
}

if(null == this)有什么区别?Somevariable)和if(this).Somevariable ==

从代码的角度来看它们是相同的。有些人更喜欢第一种风格,因为如果你犯了错误,输入=而不是==,你会得到一个错误

绝对没有任何区别。除了你觉得哪个更好看。

它是C' c++世界的遗物,其中:

if(null = someVariable)
{
}

将给出一个错误。但是:

if(someVariable = null)
{
}

不会。

这两个if的结果与您的示例中的结果相同。

一个更相关的例子是:
   string text = null;
   if(text.Equals("something"))
   {
   }

在这里,你将得到一个NullReferenceException,所以另一种避免这种情况的方法是颠倒比较:

   string text = null;
   if("something".Equals(text))
   {
   }

这样,您就知道常量"something"将始终有效,并且任何可比项都将工作,因为源对象是有效的。