关于检查空值的问题

Abe*_*ler 3 .net c#

我和我的一位同事讨论了检查空值的问题.

他认为"在某些情况下"下面的代码会给他一个空值异常:

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

}
Run Code Online (Sandbox Code Playgroud)

但如果将代码更改为此,则不会出现错误:

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

}
Run Code Online (Sandbox Code Playgroud)

我告诉他这不可能发生,但他发誓修复了他的代码.是否有任何可能导致上述更改可能导致错误的情况?

Jon*_*eet 12

没有字符串,没有.你可以用写得不好的==重载来做到这一点:

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...");
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

当然,如果您将等于运算符更改为:

public static bool operator ==(NaughtyType first, NaughtyType second)
{
    return second.Equals(first);
}
Run Code Online (Sandbox Code Playgroud)

然后你的同事代码会失败,但你的代码不会!基本上如果你正确地重载运算符 - 或者使用不重载运算符的类型 - 这不是问题.如果你的同事一直声称他遇到了它,请让他重现它.他当然不应该要求你根据他无法证明的东西来降低可读性(我相信大多数人会发现第一种形式更具可读性).


Hen*_*man 6

我认为这是C/C++中"最佳实践"的遗留问题,因为使用'='代替'=='是一个容易犯的错误:

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

if(null = test)  // C compiler error, null cannot be assigned to 
Run Code Online (Sandbox Code Playgroud)

在C#中,它们都会产生错误.

  • 是的,我怀疑有人声称"编码错误",试图提升他的编码偏好. (2认同)