.NET 6新特性试用 | ArgumentNullException卫语句
前言
在前面的文章中(《可空引用類型》),我們介紹過編譯器會(huì)幫我們檢查空引用,但是僅僅是警告。最好的方式還是在運(yùn)行時(shí)用衛(wèi)語句進(jìn)行檢查:
private?void?Test(WeatherForecast?weatherForecast) {if?(weatherForecast?==?null){?throw?new?ArgumentNullException(nameof(weatherForecast));} }在.NET 6中,在ArgumentNullException類中添加了一個(gè)名為ThrowIfNull的新靜態(tài)方法,它允許我們快速檢查和拋出 ArgumentNullExceptions:
有意思的是,異常信息自動(dòng)帶出了參數(shù)名稱,這樣可以有效避免使用nameof用錯(cuò)參數(shù)。
那這是怎么做到的呢?
原理探究
查看ThrowIfNull的定義,可以看到還有一個(gè)默認(rèn)參數(shù),使用了CallerArgumentExpression屬性聲明:
public?static?void?ThrowIfNull([NotNull]?object??argument,?[CallerArgumentExpression("argument")]?string??paramName?=?null)在編譯時(shí),編譯器會(huì)把上面的代碼編譯成如下形式,傳入了參數(shù)名:
ArgumentNullException.ThrowIfNull(weatherForecast,?"weatherForecast");原理利用
很可惜,.NET 6沒有提供更多類似ThrowIfNull的幫助方法,但是我們可以利用CallerArgumentExpression實(shí)現(xiàn)自己的幫助類來簡(jiǎn)化衛(wèi)語句。
比如:
public?class?ArgumentExceptionHelper?{public?static?void?ThrowIfNullOrEmpty(string??argument,?[CallerArgumentExpression("argument")]?string??paramName?=?null){if(string.IsNullOrEmpty(?argument))throw?new?ArgumentNullException(paramName);}public?static?void?ThrowIfOutOfRange(bool?argument,?[CallerArgumentExpression("argument")]?string??paramName?=?null){if?(argument)throw?new?ArgumentOutOfRangeException(paramName);} }//使用 ArgumentExceptionHelper.ThrowIfNullOrEmpty(name);ArgumentExceptionHelper.ThrowIfOutOfRange(age?<=?0);最為奇妙的是,CallerArgumentExpression的功能是表示一個(gè)參數(shù)將傳遞給另一個(gè)參數(shù)的表達(dá)式作為字符串捕獲。,錯(cuò)誤提示的不是參數(shù)名稱,而是實(shí)際傳入的表達(dá)式,因此更清晰。
例如下面的錯(cuò)誤提示Age<=0:
結(jié)論
在.NET 6之前,.NET中已有三個(gè)[Caller*]屬性可用:
[CallerMemberName]
[CallerFilePath]
[CallerLineNumber]
詳細(xì)介紹請(qǐng)參看:https://docs.microsoft.com/en-us/dotnet/api/system.runtime.compilerservices.callermembernameattribute
利用這些屬性,可以讓編譯器“神奇地”填充它們,幫助我們輕松獲取調(diào)用者信息。
如果你覺得這篇文章對(duì)你有所啟發(fā),請(qǐng)幫忙點(diǎn)個(gè)贊或者在看
總結(jié)
以上是生活随笔為你收集整理的.NET 6新特性试用 | ArgumentNullException卫语句的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 如何修改 asp.net core 5
- 下一篇: MAUI中构建跨平台原生控件实现