前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >C#中烦人的Null值判断竟然这样就被消灭了

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

作者头像
依乐祝
发布2020-12-28 11:50:52
1.1K0
发布2020-12-28 11:50:52
举报
文章被收录于专栏:依乐祝依乐祝依乐祝

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)
{
  // ...
}

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2020-12-25 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • NotNullAttribute
  • 自定义解决方案
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档