本网站(662p.com)打包出售,且带程序代码数据,662p.com域名,程序内核采用TP框架开发,需要联系扣扣:2360248666 /wx:lianweikj
精品域名一口价出售:1y1m.com(350元) ,6b7b.com(400元) , 5k5j.com(380元) , yayj.com(1800元), jiongzhun.com(1000元) , niuzen.com(2800元) , zennei.com(5000元)
需要联系扣扣:2360248666 /wx:lianweikj
C#中烦人的Null值判断竟然这样就被消灭了
iamitnan · 478浏览 · 发布于2020-12-25 +关注

Null值检查应该算是开发中最常见且烦人的工作了吧,有人反对吗?反对的话请右上角关门不送。这篇文章就教大家一招来简化这个烦人又不可避免的工作。

说明,提供思路的一篇文章招来这么多非议,为何啊?

罗嗦话不多说,先看下面一段简单的不能再简单的null值判断代码:

public void DoSomething(string message)
{
  if(message == null)
    throw new ArgumentNullException();
    
    // 
}


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

public void DoSomething(string message)
{
  Assert.That(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 类并定义一个隐式运算符,然后我们可以处理赋值。

public class NotNull{
    public NotNull(T value)
    {
        this.Value = value;
    }

    public T Value { get; set; }

    public static implicit operator NotNull(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 message) // <--- NotNull is used here
{
    Console.WriteLine(message.Value);
}


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

<pre data-cke-widget-data="{"code":"public void DoSomething(NotNull

message, NotNullid, NotNullproduct)\n{\n  // ...\n}","classes":[]}" data-cke-widget-upcasted="1" data-cke-widget-keep-attr="0" data-widget="codeSnippet">public void DoSomething(NotNull message, NotNull id, NotNull product) {   //  }


 


c#

相关推荐

PHP实现部分字符隐藏

沙雕mars · 1325浏览 · 2019-04-28 09:47:56
Java中ArrayList和LinkedList区别

kenrry1992 · 908浏览 · 2019-05-08 21:14:54
Tomcat 下载及安装配置

manongba · 970浏览 · 2019-05-13 21:03:56
JAVA变量介绍

manongba · 962浏览 · 2019-05-13 21:05:52
什么是SpringBoot

iamitnan · 1086浏览 · 2019-05-14 22:20:36
加载中

0评论

评论
分类专栏
小鸟云服务器
扫码进入手机网页