異常的處理
新版本的C#支持nullable功能,如果一個可空的對象,沒有進行空值判斷的話,IDE會有報警提示。
借助下面的一些特性標識,能夠進行null值的判斷。
對函數內引用的屬性進行異常判斷
通過ArgumentNullException.ThrowIfNull。
private async void OnRestore()
{
ArgumentNullException.ThrowIfNull(SelectedItems);
var items = SelectedItems.Cast<UrlInfo>();
items.ForEach(s => s.IsDeleted = false);
await _helper.UpdateDataInfos(items);
OnRefresh();
}
當返回值為true或false時,某個屬性不為null
CanEdit返回值為true時,SelectedItem不為空。
[System.Diagnostics.CodeAnalysis.MemberNotNullWhen(true, nameof(SelectedItem))]
private bool CanEdit()
{
return SelectedItem != null;
}
如果想表示返回值為false時,SelectedItem不為空的話,修改為:
[System.Diagnostics.CodeAnalysis.MemberNotNullWhen(false, nameof(SelectedItem))]
private bool CanEdit()
{
return SelectedItem != null;
}
當返回值為true或false時,傳入的這個參數不為null
下面的代碼,傳入的參數判斷結果為true的時候,就會標識為這個參數不為null
public static bool IsContainText([NotNullWhen(true)]string? value)
{
return !string.IsNullOrEmpty(value);
}
同樣,如何想傳入的參數判斷結果為false的時候,標識這個參數不為null的話,修改為:
public static bool IsContainText([NotNullWhen(false)]string? value)
{
return !string.IsNullOrEmpty(value);
}

浙公網安備 33010602011771號