当前位置:网站首页>在 C# 中如何检查参数是否为 null
在 C# 中如何检查参数是否为 null
2022-08-09 16:09:00 【dotNET跨平台】
前言
前不久,微软宣布从 C# 11 中移除参数空值检查功能,该功能允许在方法开始执行之前,在参数名称的末尾提供参数空值检查(!!操作符)。

那么,在 C# 中如何检查参数是否为 null 呢?
1. == null
这个可能是大家第一个就会想到的方法。
使用相等运算符符检查两个操作符是否相等:
if(user == null)
throw new ArgumentNullException(nameof(user));但是,==运算符可以被重载,可能导致检查空值的结果和预想的不一致:
public class User
{
...
public static bool operator ==(User user1, User user2)
{
return false;
}
}
var user = null;
if(user == null) // false
throw new ArgumentNullException(nameof(user));这时,可以使用is运算符。
2. is null
is运算符检查表达式的结果是否与给定的类型相匹配。将表达式与 null 匹配时,编译器保证不会调用用户重载的==运算符:
public class User
{
...
public static bool operator ==(User user1, User user2)
{
return false;
}
}
var user = null;
if(user is null) // true
throw new ArgumentNullException(nameof(user));3. 模式匹配
“模式匹配”是一种测试表达式是否具有特定特征的方法。模式匹配最常见的方案之一是确保值不是 null:
int? maybe = 12;
if (maybe is int number)
{
Console.WriteLine($"The nullable int 'maybe' has the value {number}");
}
else
{
Console.WriteLine("The nullable int 'maybe' doesn't hold a value");
}但是,对于检查空值功能来说,这种方式可读性较差。
4. ArgumentNullException.ThrowIfNull
如果你使用的是 C# 10,建议你使用ArgumentNullException.ThrowIfNull方法检查空值:
ArgumentNullException.ThrowIfNull(user);使用该方法的好处之一是在异常消息中会自动包含参数名称。
方法详细介绍可参看《.NET 6新特性试用 | ArgumentNullException卫语句》
结论
你是否还知道其他检查空值的方法,欢迎留言讨论。
添加微信号【MyIO666】,邀你加入技术交流群
边栏推荐
- Fees and inquiry methods of futures account opening exchanges
- 称重模块的分类及特点
- 2.1, pay attention to the network based on parallel context scenario text image super-resolution
- Reasons for slow startup of IDEA (1)
- After the WeChat developer tool program is developed, no error is reported, but the black screen "recommended collection"
- Jenkins使用pipeline部署服务到远程服务器
- 期货开户流程和手续费如何调整
- PADS generates bitmap
- How bad can a programmer be?
- HR to get the entry date RP_GET_HIRE_DATE
猜你喜欢

The Chinese Academy of Sciences slaps Google in the face: ordinary computers catch up with quantum superiority, and can solve calculations that would have taken 10,000 years in a few hours...

MySQL 5.5系列安装步骤教程(图解版)

HR获取入职日期 RP_GET_HIRE_DATE

.NET 6 study notes (4) - Solve the Nullable warning in VS2022

原油等特殊期货开户要求和豁免

期货开户交易所的手续费和查询方法

A51 - 基于STM32的DHT11和LCD显示串口通信仿真

B44 - 基于stm32蓝牙智能语音识别分类播报垃圾桶

Reasons for slow startup of IDEA (1)

图像几何校正
随机推荐
dichotomy
Prometheus完整安装
QT工程编译过程学习
ceph部署
A51 - 基于STM32的DHT11和LCD显示串口通信仿真
Smart Light Pole Gateway Smart Transportation Application
MySQL索引的B+树到底有多高?
【开源教程4】疯壳·开源编队无人机-OPENMV 脚本烧写
反转链表的多种写法(武器库了属于是)
聊聊基于docker部署的mysql如何进行数据恢复
Lagrange interpolation formula matlab implementation
shopee引流方式有哪些,商家如何为自己店铺做引流?
总结了 110+ 公开专业数据集
Redis Cache Expiration and Retirement Policy
ABP 6.0.0-rc.1的新特性
2.1、基于并行上下文注意网络的场景文本图像超分辨率
TMin - TMin是否产生溢出
2019强网杯高明的黑客
消防安全培训|暑期“消防课堂”,开讲!
期货开户应该了解的行内知识