我正在尝试验证多个配置参数,理想情况下一次报告所有问题。其形式类似于:
var isValid = true;
if (arg1 == null)
{
// logger.LogError...
isValid = false;
}
if (arg2 == null)
{
// logger.LogError...
isValid = false;
}
if (!isValid)
{
return;
}
arg1.DoSomething(); // possible null warning
现在,如果我在单个参数为空时单独中止,则没有问题:空分析成功检测到已检查该参数,无需发出警告。不幸的是,这意味着我无法一次报告多个错误,用户需要进行多个编辑运行循环才能解决所有问题。
或者,我可以使用空值包容运算符 ( !
) 强制忽略空值警告。但这让我很容易忘记空值检查或在以后意外删除空值检查。
我可以鱼与熊掌兼得吗?有没有一种更简洁的模式可以进行多参数验证,而无需牺牲可空性分析?
完整示例:
using System;
#nullable enable
public class Program
{
public static void Main()
{
Warning();
NoWarning();
}
public static void Warning()
{
string? canBeNull = Random.Shared.Next(2) == 1 ? "not-null" : null;
string? canBeNull2 = Random.Shared.Next(2) == 1 ? "not-null" : null;
var isValid = true;
if (canBeNull == null)
isValid = false;
if (canBeNull2 == null)
isValid = false;
if (!isValid)
return;
Console.WriteLine(canBeNull.Length);
}
public static void NoWarning()
{
string? canBeNull = Random.Shared.Next(2) == 1 ? "not-null" : null;
string? canBeNull2 = Random.Shared.Next(2) == 1 ? "not-null" : null;
if (canBeNull == null)
return;
if (canBeNull2 == null)
return;
Console.WriteLine(canBeNull.Length);
}
}
您可以使用辅助验证器方法检查所有内容并合并错误消息,并将[NotNullWhen]属性应用于每个参数。
它并没有真正“直接”解决问题,我认为这更像是一种“变通方法” - 只是为了免责声明。
如果你有这样的方法:
然后检查可空候选,如果通过,则使用非空输出。
注意:这也可以作为静态方法工作,但据我所知不能作为扩展方法工作(因为 out 关键字)。