我正在学习 C# 并尝试处理大量涌入的“a
could be null
”警告。
我想知道,由于当某些东西为 null 时出错是很常见的情况,无论是通过从函数返回还是抛出异常,C# 是否为这种情况提供了某种语法糖?
我想到的示例:int a = obtainA() ??? { Console.WriteLine("Fatal error;") return };
(这不是真正的代码)
我知道 ??
和 ??=
运算符,但它们在这里似乎没什么用,我也没有找到更好的。
如果不是,我们最接近模拟的是什么?有没有比写以下内容更好的方法了?
int? nullableA = obtainA();
int a;
if (nullableA.HasValue) {
a = nullableA.Value;
}
else {
Console.WriteLine("Fatal error");
return;
}
/* use a, or skip defining a and trust the static analyzer to notice nullableA is not null */
最佳答案
由于 throw expressions,自 C# 7 以来,“or_throw”可以通过 ??
运算符实现介绍:
int? i = null;
int j = i ?? throw new Exception();
可以使用 ArgumentNullException.ThrowIfNull
实现另一种抛出方法:
#nullable enable
int? i = null;
ArgumentNullException.ThrowIfNull(i);
int j = i.Value; // no warning, compiler determine that i can't be null here
您还可以使用 attributes for null-state static analysis interpreted by the C# compiler 编写自己的方法来支持可空流分析(如 ArgumentNullException.ThrowIfNull
所做的那样) :
#nullable enable
int? i = null;
if (IsNullAndReport(i)) return;
int j = i.Value; // no warning, compiler determine that i can't be null here
bool IsNullAndReport([NotNullWhen(false)]int? v, [CallerArgumentExpression(nameof(i))] string name = "")
{
if (v is null)
{
Console.WriteLine($"{name} is null;");
return true;
}
return false;
}
和模式匹配的方法:
int? i = null;
if (i is { } j) // checks if i is not null and assigns value to scoped variable
{
// use j which is int
}
else
{
Console.WriteLine("Fatal error");
return;
}
https://stackoverflow.com/questions/75055180/