• C#中烦人的Null值判断竟然这样就被消灭了


    Null值检查应该算是开发中最常见且烦人的工作了吧,有人反对吗?反对的话请右上角关门不送。这篇文章就教大家一招来简化这个烦人又不可避免的工作。
    罗嗦话不多说,先看下面一段简单的不能再简单的null值判断代码:

    1. public void DoSomething(string message)
    2. {
    3. if(message == null)
    4. throw new ArgumentNullException();
    5. // ...
    6. }

    方法体的每个参数都将用if语句进行检查,并逐个抛出 ArgumentNullException 的异常。
    关注我的朋友,应该看过我上篇《一个小技巧助您减少if语句的状态判断》的文章,它也是简化Null值判断的一种方式。简化后可以如下所示:

    1. public void DoSomething(string message)
    2. {
    3. Assert.That<ArgumentNullException>(message == null, nameof(DoSomething));
    4. // ...
    5. }

    但是还是很差强人意。


    **

    NotNullAttribute

    这里你可能想到了 _System.Diagnostics.CodeAnalysis_ 命名空间下的这个 [NotNull] 特性。这不会在运行时检查任何内容。它只适用于CodeAnalysis,并在编译时而不是在运行时发出警告或错误!

    1. public void DoSomething([NotNull]string message) // Does not affect anything at runtime.
    2. {
    3. }
    4. public void AnotherMethod()
    5. {
    6. DoSomething(null); // MsBuild doesn't allow to build.
    7. string parameter = null;
    8. DoSomething(parameter); // MsBuild allows build. But nothing happend at runtime.
    9. }

    自定义解决方案

    这里我们将去掉用于Null检查的if语句。如何处理csharp中方法参数的赋值?答案是你不能!. 但你可以使用另一种方法来处理隐式运算符的赋值。让我们创建 NotNull 类并定义一个隐式运算符,然后我们可以处理赋值。

    1. public class NotNull<T>
    2. {
    3. public NotNull(T value)
    4. {
    5. this.Value = value;
    6. }
    7. public T Value { get; set; }
    8. public static implicit operator NotNull<T>(T value)
    9. {
    10. if (value == null)
    11. throw new ArgumentNullException();
    12. return new NotNull(value);
    13. }
    14. }

    现在我们可以使用NotNull对象作为方法参数.

    1. static void Main(string[] args)
    2. {
    3. DoSomething("Hello World!"); // Works perfectly 👌
    4. DoSomething(null); // Throws ArgumentNullException at runtime.
    5. string parameter = null;
    6. DoSomething(parameter); // Throws ArgumentNullException at runtime.
    7. }
    8. public static void DoSomething(NotNull<string> message) // <--- NotNull is used here
    9. {
    10. Console.WriteLine(message.Value);
    11. }

    如您所见, DoSomething() 方法的代码比以前更简洁。也可以将NotNull类与任何类型一起使用,如下所示:

    1. public void DoSomething(NotNull<string> message, NotNull<int> id, NotNull<Product> product)
    2. {
    3. // ...
    4. }

    感谢您的阅读,我们下篇文章见,我是依乐祝,我为合肥.NET技术社区“带盐”~
    参考自:https://enisn.medium.com/never-null-check-again-in-c-bd5aae27a48e

     

  • 相关阅读:
    Windows11不插耳机、音箱提示无法找到输出设备的问题解决方法
    秋染田野稻菽飘香 国稻种芯·中国水稻节:河北各地农业丰收
    Objective-C 基础教程第六章,源文件组织
    软件测试周刊(第83期):当你感觉忙得没时间休息,就是你最需要找时间休息的时候。 ​​​
    [JAVAee]SpringBoot配置文件
    《算法系列》之回溯
    学习C++第二十四课--成员函数模板,模板显示实例化与声明笔记
    获取pandas中的众数
    十三、企业开发(2)
    RecursionError: maximum recursion depth exceeded情况解决之一
  • 原文地址:https://blog.csdn.net/biyusr/article/details/126864531