gpt4 book ai didi

c# - 空条件运算符 and !=

转载 作者:可可西里 更新时间:2023-11-01 03:08:49 25 4
gpt4 key购买 nike

随着Null-Conditional Operators的引入在 C# 中,对于以下评估,

if (instance != null && instance.Val != 0)

如果我这样重写,

if (instance?.Val != 0)  

如果实例是空引用,它将被评估为true;它表现得像

if (instance == null || instance.Val != 0)

那么使用这种新语法重写评估的正确方法是什么?

编辑:

instance 是从 JSON 反序列化的大对象的字段。类似这样的代码有好几段,首先检查字段是否在JSON中,如果是,则检查Val属性是否不等于常量,只有两个条件都为真,才做一些操作。

代码本身可以重构,使逻辑流程更“有意义”,正如 Peter 在他的评论中所指出的,尽管在这个问题中我对如何使用 null-conditional operators 感兴趣!=

最佳答案

使用 Null-Conditional 运算符,返回值始终为 null

if ((instance?.Val ?? 0) != 0)

如果 instance 为 null,则 instance?.Val 也将为 null(在您的情况下可能是 int?)。因此,在与任何内容进行比较之前,您应该始终检查是否存在空值:

if ((instance?.Val ?? 0) != 0)

这意味着:如果 instance?.Val 为 null(因为 instance 为 null)则返回 0。否则返回 instance.Val。接下来将此值与 0(不等于)进行比较。

关于c# - 空条件运算符 and !=,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44793887/

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