条件语句的区别 [英] Conditional Statements difference

查看:115
本文介绍了条件语句的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有以下两种说法有什么区别

Is there any difference between below two statements

if (null != obj)

if (obj != null)

编辑:

如果两者相同对待,这将是preferable?

if both treated same which will be preferable?

感谢

推荐答案

这里的区别是code产生的。两个不会产生完全相同的code,但在实践中,这将有两个语句的对结果没有任何轴承或性能

The difference here is the code generated. The two will not generate the exact same code, but in practice this will have no bearing on the results or performance of the two statements.

不过,如果你创建自己的类型,并覆盖不平等运营商,做的不好的话,那将此事。

However, if you create your own types, and override the inequality operator, and do a poor job, then it will matter.

考虑一下:

public class TestClass
{
    ...

    public static bool operator !=(TestClass left, TestClass right)
    {
        return !left.Equals(right);
    }
}

在这种情况下,如果第一个参数到操作为空,即如果(空!= OBJ),那么它将与崩溃的NullReferenceException

In this case, if the first argument to the operator is null, ie. if (null != obj), then it will crash with a NullReferenceException.

总结一下:


  • 生成的code是不同

  • 的性能和最终的结果应该是相同的

    • 除非你已在所涉及的类别划分code

    现在,我想你问的原因是,你已经看到C,通常有code这样的code:

    Now, the reason I think you're asking is that you've seen code from C, which typically had code like this:

    if (null == obj)
    

    请注意,我切换到平等检查在这里。其原因是,在与旧的C编译器编写的程序(这些天,他们往往会抓住这个问题),一个频繁的错误将是左右切换后,忘了平等的人物之一,即得。这样的:

    Note that I switched to equality check here. The reason is that a frequent bug in programs written with old C compilers (these days they tend to catch this problem) would be to switch it around and forget one of the equal characters, ie. this:

    if (obj = null)
    

    本受让人来的变量,而不是比较吧。打击这种错误的最好办法,回去以后,将切换左右吧,因为你不能指定任何,它不是一个变量。 IE浏览器。这将无法编译:

    This assigns null to the variable instead of comparing it. The best way to combat this bug, back then, would be to switch it around, since you can't assign anything to null, it's not a variable. ie. this would fail to compile:

    if (null = obj)
    

    这篇关于条件语句的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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