首页 > 解决方案 > C# NullChecking: a is null vs object.Equals(a, null)

问题描述

当前版本的 C#(高于 7.1)有以下两种方法来检查变量是否为空:

// first one
object.Equals(a, null);

// second one
a is null;

我想知道,每种方式的优点是什么。是否有任何特殊情况可以同时使用它们?

标签: c#.netisnull

解决方案


等于证明身份,这意味着对象完全相同。您可以覆盖 Equals,在这种情况下您可以检查它们的属性。(在 object.Equals 的情况下,您证明身份)。


如果 expr 不为空,则 is 表达式为真,并且以下任何一项为真:(SRC:https ://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/is )

expr 是与 type 相同类型的实例。

expr is an instance of a type that derives from type. In other words, the result of expr can be upcast to an instance of type.

expr has a compile-time type that is a base class of type, and expr has a runtime type that is type or is derived from type. The compile-time type of a variable is the variable's type as defined in its declaration. The runtime type of a variable is the type of the instance that is assigned to that variable.

expr is an instance of a type that implements the type interface.

在这里您可以找到如何覆盖 Equals: https ://docs.microsoft.com/de-de/dotnet/api/system.object.equals?view=netframework-4.8

这里有一些例子:


    public class Word
{
    public string Name;

    public Word(string name)
    {
        Name = name;
    }

    //Euqals is no overriden
    public override bool Equals(object obj)
    {
        return base.Equals(obj);
    }


    public class OtherClass
    {
        public OtherClass()
        {
            Word word = new Word("word");
            Word otherWord = new Word("word");
            string a = null;

            var r = a == null; //true
            var r2 = object.Equals(a, null);//true      
            var r3 = word.Name is string; //true
            var r4 = word.Name is Word; //false
            var r5 = word.Equals(otherWord); //false
        }
    }

如果您在班级中覆盖 equals :


public class Word
{
    public string Name;

    public Word(string name)
    {
        Name = name;
    }

    //Override Equals
    public override bool Equals(object obj)
    {
        if ((obj == null) || !this.GetType().Equals(obj.GetType()))
        {
            return false;
        }
        else
        {
            Word thisWord = (Word) obj;
            return (Name == thisWord.Name) /* && (Other properties)*/;
        }
    }


    public class OtherClass
    {
        public OtherClass()
        {
            Word word = new Word("word");
            Word otherWord = new Word("word");
            string a = null;

            var r = a == null; //true
            var r2 = object.Equals(a, null);//true      
            var r3 = word.Equals(otherWord); //true
        }
    }

推荐阅读