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

 

 

出處:https://www.cnblogs.com/yilezhu/p/14177595.html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM