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));
- // ...
- }
但是还是很差强人意。

**
这里你可能想到了 _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 类并定义一个隐式运算符,然后我们可以处理赋值。
- 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
(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)
- {
- // ...
- }
感谢您的阅读,我们下篇文章见,我是依乐祝,我为合肥.NET技术社区“带盐”~
参考自:https://enisn.medium.com/never-null-check-again-in-c-bd5aae27a48e