C#开发-Null的整型数值比较

大家都知道整数类型、浮点数类型、布尔类型比较的规则。这在各个语言中都是通用的。但是有谁知道Null类型和整型比较的结果呢?

我在.NET8.0下编写了这个测试程序来解释Null和整型比较的结果。

cs 复制代码
int? count = null;
bool compare1 = count > 2;
bool compare2 = count > 0;
bool compare3 = count > -1;

Console.WriteLine($"{nameof(compare1)}: {compare1}");
Console.WriteLine($"{nameof(compare2)}: {compare2}");
Console.WriteLine($"{nameof(compare3)}: {compare3}");

bool compare4 = count < 2;
bool compare5 = count < 0;
bool compare6 = count < -1;

Console.WriteLine($"{nameof(compare4)}: {compare4}");
Console.WriteLine($"{nameof(compare5)}: {compare5}");
Console.WriteLine($"{nameof(compare6)}: {compare6}");

bool compare7 = count == 2;
bool compare8 = count == 0;
bool compare9 = count == -1;

Console.WriteLine($"{nameof(compare7)}: {compare7}");
Console.WriteLine($"{nameof(compare8)}: {compare8}");
Console.WriteLine($"{nameof(compare9)}: {compare9}");

运行结果如下所示。

bash 复制代码
compare1: False
compare2: False
compare3: False
compare4: False
compare5: False
compare6: False
compare7: False
compare8: False
compare9: False

我们可以看到null无论是跟正数比较还是跟零或负数比较,比较返回的结果总是false。

根据这样的特性我们可以用来简化检查非空的代码。

这是优化前的代码。

cs 复制代码
if (nullableList != null && nullableList.Count > num)

{
    // do something
}

这是优化后的代码。

cs 复制代码
if (nullableList?.Count > num)

{
    // do something
}

利用好跟null比较总是返回false的特性,我们可以优化项目里大量检查非空的代码。

相关推荐
9毫米的幻想5 分钟前
【Linux系统】—— 冯诺依曼体系结构与操作系统初理解
linux·运维·服务器·c语言·c++
code_shenbing17 分钟前
WPF 实现虚拟键盘
c#·wpf
勤奋的凯尔森同学6 小时前
webmin配置终端显示样式,模仿UbuntuDesktop终端
linux·运维·服务器·ubuntu·webmin
软件黑马王子6 小时前
C#初级教程(4)——流程控制:从基础到实践
开发语言·c#
丁卯4047 小时前
Go语言中使用viper绑定结构体和yaml文件信息时,标签的使用
服务器·后端·golang
chengooooooo7 小时前
苍穹外卖day8 地址上传 用户下单 订单支付
java·服务器·数据库
人间打气筒(Ada)8 小时前
MySQL主从架构
服务器·数据库·mysql
落笔画忧愁e9 小时前
FastGPT快速将消息发送至飞书
服务器·数据库·飞书
小冷爱学习!9 小时前
华为动态路由-OSPF-完全末梢区域
服务器·网络·华为
落幕10 小时前
C语言-进程
linux·运维·服务器