C#中烦人的Null值判断竟然这样就被消灭了
作者:依乐祝
首发自:DotNetCore实战 公众号
https://www.cnblogs.com/yilezhu/p/14177595.html
Null值检查应该算是开发中最常见且烦人的工作了吧,有人反对吗?反对的话请右上角关门不送。这篇文章就教大家一招来简化这个烦人又不可避免的工作。
说明,提供思路的一篇文章招来这么多非议,为何啊?
罗嗦话不多说,先看下面一段简单的不能再简单的null值判断代码:
public void DoSomething(string message)
{
if(message == null)
throw new ArgumentNullException();
// ...
}
方法体的每个参数都将用if语句进行检查,并逐个抛出 ArgumentNullException
的异常。
关注我的朋友,应该看过我上篇《一个小技巧助您减少if语句的状态判断》的文章,它也是简化Null值判断的一种方式。简化后可以如下所示:
public void DoSomething(string message)
{
Assert.That<ArgumentNullException>(message == null, nameof(DoSomething));
// ...
}
但是还是很差强人意。
**
NotNullAttribute
这里你可能想到了 _System.Diagnostics.CodeAnalysis_
命名空间下的这个 [NotNull] 特性。这不会在运行时检查任何内容。它只适用于CodeAnalysis,并在编译时而不是在运行时发出警告或错误!
public void DoSomething([NotNull]string message) // Does not affect anything at runtime.
{
}
public void AnotherMethod()
{
DoSomething(null); // MsBuild doesn't allow to build.
string parameter = null;
DoSomething(parameter); // MsBuild allows build. But nothing happend at runtime.
}
自定义解决方案
这里我们将去掉用于Null检查的if语句。如何处理csharp中方法参数的赋值?答案是你不能!. 但你可以使用另一种方法来处理隐式运算符的赋值。让我们创建 NotNull<T>
类并定义一个隐式运算符,然后我们可以处理赋值。
public class NotNull<T>
{
public NotNull(T value)
{
this.Value = value;
}
public T Value { get; set; }
public static implicit operator NotNull<T>(T value)
{
if (value == null)
throw new ArgumentNullException();
return new NotNull<T>(value);
}
}
现在我们可以使用NotNull对象作为方法参数.
static void Main(string[] args)
{
DoSomething("Hello World!"); // Works perfectly 👌
DoSomething(null); // Throws ArgumentNullException at runtime.
string parameter = null;
DoSomething(parameter); // Throws ArgumentNullException at runtime.
}
public static void DoSomething(NotNull<string> message) // <--- NotNull is used here
{
Console.WriteLine(message.Value);
}
如您所见, DoSomething()
方法的代码比以前更简洁。也可以将NotNull类与任何类型一起使用,如下所示:
public void DoSomething(NotNull<string> message, NotNull<int> id, NotNull<Product> product)
{
// ...
}
感谢您的阅读,我们下篇文章见~
参考自:https://enisn.medium.com/never-null-check-again-in-c-bd5aae27a48e
关注我】。(●'◡'●)
如果,您希望更容易地发现我的新博客,不妨点击一下绿色通道的【因为,我的写作热情也离不开您的肯定与支持,感谢您的阅读,我是【Jack_孟】!
本文来自博客园,作者:jack_Meng,转载请注明原文链接:https://www.cnblogs.com/mq0036/p/14188301.html
【免责声明】本文来自源于网络,如涉及版权或侵权问题,请及时联系我们,我们将第一时间删除或更改!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
2019-12-25 博客园推荐客户端 ---- Open Live Writer
2019-12-25 Win10以管理员登录,编辑c盘文件提示没有权限
2019-12-25 HttpClient在高并发场景下的优化实战
2017-12-25 活期存款利息的计算方法
2016-12-25 解决中64位Win7系统上PLSQL无法连接ORACLE的方法(PLSQL无法识别ORACLE_HOME的配置)
2012-12-25 C#命令行编译器的步骤介绍
2012-12-25 c#中csc命令的用法