【问题标题】:How to annotate a C# function to say that a parameter is not null if it returns如何注释 C# 函数以表明参数在返回时不为 null
【发布时间】:2022-12-07 06:09:14
【问题描述】:

如果字符串为空/空/空白,我有一些验证代码会抛出异常。我希望它在函数返回后向空检查系统发出信号,表明 argument 不为空。

void ThrowIfNullEmptyOrBlank(string? argument, string paramName)
    => ThrowIf(Check.Null & Check.Empty & Check.Blank, argument, paramName);

[return: NotNull] void ThrowIfNullEmptyOrBlank(string? argument, string paramName) 不对,因为我的方法没有返回值(我想我可以改变它,但这样更干净)。

void ThrowIfNullEmptyOrBlank([param: NotNull] string? argument, string paramName) 似乎也没有做到这一点。

有可能做我正在尝试的事情吗?

【问题讨论】:

  • 怎么样: string ThrowIfNullEmptyOrBlank(string? argument, string paramName) { ThrowIf(Check.Null & Check.Empty & Check.Blank, argument, paramName);返回参数; } 。编译器会知道输出不为空,您可以使用它
  • Dotnet 使用 MaybeNullWhenAttribute,但这是内部的
  • 第一个建议要求调用者将 argument 设置为此调用的结果,以便传播类型数据;我宁愿不依赖人们记得这样做。
  • 您可能需要考虑将“检查”值的逻辑与“抛出”分开。 IsNullOrWhitespace 也已经存在,它使用 [NotNullWhen],它之所以有效,是因为 Is... 方法返回一个布尔值。

标签: c# .net


【解决方案1】:

只需使用NotNullAttribute

void ThrowIfNullEmptyOrBlank([NotNull] string? argument, string paramName)
    => ThrowIf(Check.Null & Check.Empty & Check.Blank, argument, paramName);

来自Attributes for null-state static analysis interpreted by the C# compiler

可为 null 的参数、字段、属性或返回值永远不会为 null。

【讨论】:

    猜你喜欢
    • 2021-12-15
    • 2018-09-23
    • 2014-01-08
    • 2017-04-18
    • 1970-01-01
    • 2014-02-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多