简体   繁体   English

关于检查空值的问题

[英]Question about checking for null values

I just got into a debate with one of my coworkers about checking for null values. 我和我的一位同事讨论了检查空值的问题。

He SWEARS that "in certain situations" the code below would give him a null value exception: 他认为“在某些情况下”下面的代码会给他一个空值异常:

string test = null;
if(test == null) //error here
{

}

but that if changed the code to this there would be no error: 但如果将代码更改为此,则不会出现错误:

string test = null;
if(null == test) //NO error here
{

}

I told him there was no way this could happen but he swears it fixed his code. 我告诉他这不可能发生,但他发誓修复了他的代码。 Is there any possible situation where the above change could fix an error? 是否有任何可能导致上述更改可能导致错误的情况?

Not with string, no. 没有字符串,没有。 You could do so with a badly written == overload though: 你可以用写得不好的==重载来做到这一点:

using System;

public class NaughtyType
{
    public override int GetHashCode()
    {
        return 0;
    }

    public override bool Equals(object other)
    {
        return true;
    }

    public static bool operator ==(NaughtyType first, NaughtyType second)
    {
        return first.Equals(second);
    }

    public static bool operator !=(NaughtyType first, NaughtyType second)
    {
        return !first.Equals(second);
    }
}

public class Test
{    
    static void Main()
    {
        NaughtyType nt = null;
        if (nt == null)
        {
            Console.WriteLine("Hmm...");
        }
    }
}

Of course, if you changed the equality operator to this: 当然,如果您将等于运算符更改为:

public static bool operator ==(NaughtyType first, NaughtyType second)
{
    return second.Equals(first);
}

then your colleagues code would fail, but yours wouldn't! 然后你的同事代码会失败,但你的代码不会! Basically if you overload operators properly - or use types which don't overload operators - this isn't a problem. 基本上,如果您正确地重载运算符 - 或使用不重载运算符的类型 - 这不是问题。 If your colleague keeps claiming he's run into it, ask him to reproduce it. 如果你的同事一直声称他遇到了它,请让他重现它。 He certainly shouldn't be asking you to reduce readability (I believe most people find the first form more readable) on the basis of something he can't demonstrate. 他当然不应该要求你根据他无法证明的东西来降低可读性(我相信大多数人会发现第一种形式更具可读性)。

I think this is a left-over from a 'best practice' in C/C++, because using '=' instead of '==' is an easy to make mistake: 我认为这是C / C ++中“最佳实践”的遗留问题,因为使用'='代替'=='是一个容易犯的错误:

if(test = null)  // C compiler Warns, but evaluates always to false

if(null = test)  // C compiler error, null cannot be assigned to 

In C#, they both produce an error. 在C#中,它们都会产生错误。

You're right. 你是对的。 If he can reproduce this without an overloaded == operator, invite him to post it here. 如果他可以在没有重载==运算符的情况下重现这一点,请邀请他在此处发布。

The test of if (test == null) if test is a string is valid and will never give an exception. 如果test是一个字符串, if (test == null)测试是有效的,永远不会给出异常。 Both tests are also essentially exactly the same. 两种测试也基本完全相同。

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

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