在 C# 中,是否可以在不使用运算符的情况下评估变量是否不同于 null?
编写
if (variable != null) ?
例如,是否可以在不使用运算符 != 或 == 的情况下
For instance is it possible to write this
if (variable != null)
without using the operator != or == ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
好吧,我只是使用
==
(如果你想避免自定义相等运算符,也许可以转换为object
- 无论如何它都会是一个 nop 转换)比,我的钱会用
object.ReferenceEquals(obj, null)
,但你也可以使用object.Equals(obj, null)
,因为它处理null
等。为了完整性:为什么我只使用
==
/!=
?简单:编译器可以直接执行此操作。针对对象进行空检查的 IL 实际上是:就是这样。两条 IL 指令。它甚至不执行“加载 null,相等性检查” - 因为“true”的定义是“任何非 0/null”,而“false”是“0/null”。
对于像
ReferenceEquals
这样的东西,即:我知道我更喜欢哪个......
Well, I'd just use
==
(if you are trying to avoid a custom equality operator, perhaps cast toobject
- it will be a nop cast anyway)Other than than, my money would go with
object.ReferenceEquals(obj, null)
, but you could also useobject.Equals(obj, null)
since it handlesnull
etc.For completeness: why would I just use
==
/!=
? Simple: the compiler can do this directly. The IL for a null-check against an object is actually:That's it. Two IL instructions. It doesn't even do a "load null, equality check" - since the definition of "true" is "anything that isn't 0/null", and "false" is "0/null".
For something like
ReferenceEquals
, that is:I know which I prefer...
您可以使用
object.ReferenceEquals
< /a>(变量,空)
。You can use
object.ReferenceEquals
(variable, null)
.对其调用 ToString(),如果收到 System.NullReferenceException,则它为 null。 :-)
但为什么?
Call ToString() on it, if you get a System.NullReferenceException it was null. :-)
But why?
你可能真的是个混蛋并使用:
You could really be a jerk and use:
如果您不想使用运算符,您将如何检查某些内容是否为空?
到底这个问题的原因是什么?
How would you check if something is null if you do not want to use an operator ?
What's the reason for this question anyway ?
好吧,唯一符合您的描述的其他语法是使用 ??运算符,(我猜它仍然是一个运算符...)但它要么返回值,要么如果该值为 null,则返回下一个表达式值,如下所示
Well, the only other syntax that fits your description is to use the ?? operator, (which is still an operator, i gues...) but it either returns the value, or if the value is null, it returns the next expressions value as in