C# 9.0 新特性之引數非空檢查簡化
阿新 • • 發佈:2020-06-15
閱讀本文大概需要 1.5 分鐘。
引數非空檢查是縮寫類庫很常見的操作,在一個方法中要求引數不能為空,否則丟擲相應的異常。比如: ```cs public static string HashPassword(string password) { if(password is null) { throw new ArgumentNullException(nameof(password)); } ... } ``` 當異常發生時,呼叫者很容易知道是什麼問題。如果不加這個檢查,可能就會由系統丟擲未將物件引用為例項之類的錯誤,這不利於呼叫者診斷錯誤。 由於這個場景太常見了,於是我經常在我的專案中通過一個輔助類來做此類檢查。這個類用來檢查方法引數,所以命名為 Guard,主要程式碼如下: ```cs public static class Guard { public static void NotNull(object param, string paramName) { if (param is null) { throw new ArgumentNullException(paramName); } } public static void NotNullOrEmpty(string param, string paramName) { NotNull(param, paramName); if (param == string.Empty) { throw new ArgumentException($"The string can not be empty.", paramName); } } public static void NotNullOrEmpty