空条件运算符和!= [英] Null-conditional operator and !=

查看:113
本文介绍了空条件运算符和!=的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

随着空- C#中的条件运算符,用于以下评估,

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

如果我用这种方式重写它,

If I rewrite it this way,

if (instance?.Val != 0)  

如果实例为空引用,它将被评估为 true ;就像

it will be evaluated to true if instance is a null reference; It behaves like

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

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

So what is the right way to rewrite the evaluation using this new syntax?

instance是从JSON反序列化的大对象的字段.有很多这样的代码,首先检查该字段是否在JSON中,如果是,请检查Val属性是否不等于常量,只有两个条件都成立,然后执行一些操作.

instance is a field of a big object which is deserialized from JSON. There are quite a few pieces of code like this, first check if the field is in the JSON, if it is, check if the Val property does NOT equal to a constant, only both conditions are true, do some operation.

正如彼得在他的评论中指出的那样,可以对代码本身进行重构以使逻辑流程更有意义",尽管在这个问题中我对如何在!=中使用null-conditional operators感兴趣.

The code itself can be refactored to make the logical flow more "making sense" as indicated by Peter in his comment, though in this question I am interested in how to use null-conditional operators with !=.

推荐答案

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

With Null-Conditional operator returned value can always be null

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

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

If instance was null, then instance?.Val will also be null (probably int? in your case). So you should always check for nulls before comparing with anything:

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

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

This means: If instance?.Val is null (because instance is null) then return 0. Otherwise return instance.Val. Next compare this value with 0 (is not equal to).

这篇关于空条件运算符和!=的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆