作者:依樂祝
首發自: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 = https://www.cnblogs.com/yilezhu/p/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<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
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/240000.html
標籤:C#
