什么时候空检查可以抛出 NullReferenceException

问题描述

我知道一开始这似乎是不可能的,一开始对我来说也是如此,但最近我看到这种代码抛出了 NullReferenceException,所以这绝对是可能的。

不幸的是,Google 上几乎没有任何结果可以解释 foo == null 之类的代码何时会引发 NRE,这会导致难以调试和理解其发生的原因。因此,为了记录这种看似奇怪的事件可能发生的可能方式。

代码 foo == null 以何种方式抛出 NullReferenceException

解决方法

在 C# 中,您可以重载运算符以在这样的比较中添加自定义逻辑。例如:

class Test
{
    public string SomeProp { get; set; }
    
    public static bool operator ==(Test test1,Test test2)
    {
        return test1.SomeProp == test2.SomeProp;
    }

    public static bool operator !=(Test test1,Test test2)
    {
        return !(test1 == test2);
    }
}

那么这将产生一个空引用异常:

Test test1 = null;
bool x = test1 == null;
,

一个例子是 getter:

class Program
{
    static void Main(string[] args)
    {
        new Example().Test();
    }
}

class Example
{
    private object foo
    {
        get => throw new NullReferenceException();
    }

    public void Test()
    {
        Console.WriteLine(foo == null);
    }
}

此代码将产生 NullReferenceException。

,

虽然非常深奥,但可以通过 DynamicMetaObject 的自定义实现来导致这种类型的行为。这将是可能发生这种情况的一个罕见但有趣的例子:

void Main()
{
    dynamic foo = new TestDynamicMetaObjectProvider();
    object foo2 = 0;
    
    Console.WriteLine(foo == foo2);
}

public class TestDynamicMetaObjectProvider : IDynamicMetaObjectProvider
{
    public DynamicMetaObject GetMetaObject(Expression parameter)
    {
        return new TestMetaObject(parameter,BindingRestrictions.Empty,this);
    }
}

public class TestMetaObject : DynamicMetaObject
{
    public TestMetaObject(Expression expression,BindingRestrictions restrictions)
        : base(expression,restrictions)
    {
    }

    public TestMetaObject(Expression expression,BindingRestrictions restrictions,object value)
        : base(expression,restrictions,value)
    {
    }

    public override DynamicMetaObject BindBinaryOperation(BinaryOperationBinder binder,DynamicMetaObject arg)
    {
        // note it doesn't have to be an explicit throw.  Any improper property
        // access could bubble a NullReferenceException depending on the 
        // custom implementation.
        throw new NullReferenceException();
    }
}
,

实际上不是您的代码,但等待空任务也会抛出:

public class Program
{
    public static async Task Main()
    {
        var s = ReadStringAsync();
        if (await s == null)
        {
            Console.WriteLine("s is null");
        }
    }

    // instead of Task.FromResult<string>(null);
    private static Task<string> ReadStringAsync() => null;
}

但是请注意,调试器可能会错误地获取抛出语句的位置。它可能会显示在等式检查时抛出的异常,而它发生在更早的代码中。

,

foo == null 确实对运算符重载解析起作用,并且有问题的运算符没有处理传递空值的情况。我们开始考虑编写过时的 foo == null 并且更喜欢(从 Visual Basic 中获取一个页面)foo is null!(foo is null) 即将成为 full is not null 以显式内联空指针检查.

修复您的 operator== 实现。它不应该抛出,但它是。