c# - C# 是否有某种 value_or_execute 或 value_or_throw?

我正在学习 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/

相关文章:

python - Pandas 将 df.count() 结果的最后 n 行求和为一行

haskell - 减少围绕手工包装的 `Num` 类型的样板

arrays - 如何将数组的元素移动到数组的开头

c - 尝试复制有关可变参数的 printf 行为

LUA - 表中最常见的项目

r - 在 mutate 中将参数传递给 pmap

python - 无法使用调试暂停 python 进程

fortran - Fortran 能否在逻辑运算中强制遵守参数顺序?

c++ - std::variant 使用整数数组中的元素作为 std::variant 中的目标类

python - 根据条件将新数据从另一个 Dataframe 添加到 Dataframe