gpt4 book ai didi

c# - 空检查何时可以引发NullReferenceException

转载 作者:行者123 更新时间:2023-12-03 07:34:14 25 4
gpt4 key购买 nike

我知道这乍看起来似乎是不可能的,一开始对我来说也是如此,但是最近我确实看到这种代码抛出了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;

关于c# - 空检查何时可以引发NullReferenceException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65583530/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com