简体   繁体   English

C# 忽略 null 检查?

[英]C# ignores null check?

Who can explain to me this irrational lame beauty of C# logic in blazor-server?谁能向我解释一下 blazor-server 中 C# 逻辑的这种非理性的蹩脚之美?

在此处输入图像描述

What is club , and does it perhaps have a static == operator overload that is not null-safe?什么是club ,它是否可能有一个不是空安全的 static ==运算符重载? For example, the following is possible and broken:例如,以下情况是可能的并且是错误的:

bool == (Foo x, Foo y) => x.Id == y.Id;

It is broken because it doesn't consider that x and/or y could be null .它被破坏了,因为它不认为x和/或y可能是null Using club == null will call this broken operator, causing a NRE.使用club == null将调用此损坏的运算符,从而导致 NRE。

A good way to check is to use club is object instead of club != null , as the is object / is null syntax never calls static == operator overloads. A good way to check is to use club is object instead of club != null , as the is object / is null syntax never calls static == operator overloads.

Maybe You should compare club to null like this:也许您应该像这样将clubnull进行比较:

if (!(club is null) && club.Id > 0)

I think NullReferenceException is caused by == operator, which can use methods that are not "null safe".我认为 NullReferenceException 是由==运算符引起的,它可以使用非“空安全”的方法。

To ensure the reference is null you can use:为确保参考为 null,您可以使用:

ReferenceEquals(myObject, null)

It is a static method from the Object class itself so basically it can be used everywhere.它是 Object class 本身的 static 方法,因此基本上可以在任何地方使用。

Most of the time it will give you the same result as:大多数情况下,它会给你相同的结果:

myObject == null

But since the "==" can be overloaded you can have strange behavior.但是由于“==”可以被重载,你可能会有奇怪的行为。 See operator overload .请参阅运算符重载

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

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