1. 程式人生 > WINDOWS開發 >C# 9.0 新特性預覽 - 空引數校驗

C# 9.0 新特性預覽 - 空引數校驗

C# 9.0 新特性預覽 - 空引數校驗

前言

隨著 .NET 5 釋出日期的日益臨近,其對應的 C# 新版本已確定為 C# 9.0,其中新增加的特性(或語法糖)也已基本鎖定,本系列文章將向大家展示它們。

目錄

[C# 9.0 新特性預覽 - 型別推導的 new]
[C# 9.0 新特性預覽 - 空引數校驗]
[C# 9.0 新特性預覽 - Lambda 中的棄元]
[C# 9.0 新特性預覽 - Record 型別]
[C# 9.0 新特性預覽 - 模式匹配的改善]
[C# 9.0 新特性預覽 - 其他小的變化]

簡便的空引數校驗 (Simplified Null Argument Checking)

目的

這個特性主要是為了更簡便的檢查方法的引數是否為 null 並丟擲?ArgumentNullExceptiony 異常。

語法

語法很簡單,在引數名後加個歎號即可:

void M(string name!) {
    ...
}

以上程式碼會被翻譯為:

void M(string name) {
    if (name is null) {
        throw new ArgumentNullException(nameof(name));
    }
    ...
}

想必有些同學已經從上面程式碼看出來了,這個生成的空校驗,只是校驗引數是否為 null,這也就意味著它無法在值型別上使用,以下程式碼將報錯:

// Error: 無法在值型別引數上使用!操作符
void G<T>(T arg!) where T : struct {

}

當然,可空的值型別是可以的,但是編譯器會提示一條警告,提示你在可空型別上進行了空檢查:

// Warning: 將顯式null檢查與可為null的型別結合使用
void M(int? x!) { 
}

類似的,在引數擁有預設值的情況下,也會提示警告

// Warning: 引數 ‘x‘ 進行了空檢查但是它預設為空
void M(string x! = null) { 
}

構造方法的場景

在構造方法的場景下,空引數校驗將發生在任何其他程式碼的前面,包括:

  • 對其他構造方法的鏈式呼叫,即 this() 或 base()
  • 在構造方法內的隱式欄位初始化

舉個例子:

class C {
    string field = GetString();
    C(string name!): this(name) {
        ...
    }
}

以上程式碼會大致翻譯為以下虛擬碼:

class C {
    C(string name)
        if (name is null) {
            throw new ArgumentNullException(nameof(name));
        }
        field = GetString();
        :this(name);
        ...
}

Lambda 的場景

這個特性在 lambda 中也可以使用

void G() {
    Func<string,string> s = x! => x;
}

不可以使用的場景

這個特性只能用於有方法體的方法中,也就意味著它不能用於抽象方法、介面、委託和部分方法。
以下程式碼編譯器會報錯:

interface C
{
    public int M(string x!);// ERROR
}

不能用於屬性。因為屬性 setter 中的 value 是隱式的,不會出現在引數列表中,所以此特性不適用於屬性。

string FirstName! { get; set; } // ERROR

不能用於 out / ref / in 的引數

public void M(out string x!) {} // ERROR

參考

[Proposal: Simplified Null Argument Checking]
[Unit test: NullCheckedParameterTests.cs]
[LDM-2019-07-10.md]