【问题标题】:Using c# Nullable Reference Type annotations from different assembly使用来自不同程序集的 c# Nullable Reference Type 注释
【发布时间】:2021-06-24 09:14:34
【问题描述】:

我使用 c# 8 "Nullable Reference Types" feature 创建了一个空保护。

我将它放在Common 程序集中,并从App 程序集中调用它。两个程序集都有<Nullable>enable</Nullable>

我的.editorconfigdotnet_diagnostic.CA1062.severity = warning

Common 程序集中,Common/Guard.cs

using System;
using System.Diagnostics.CodeAnalysis;
namespace Common {
  public static class Guard {

    public static void IsNotNull([NotNull] object? arg, string? argName) =>
      _ = arg ?? throw new ArgumentNullException(argName);

  }
}

在应用程序集中,App/Printer.cs:

using System;
using Common;
namespace App {
  public class Printer {

    public void PrintUpper(string text) {
      Guard.IsNotNull(text, nameof(text));
      Console.WriteLine(text.ToUpper());   // <--- CA1062
    }

    // it works when inside the same assembly:
    //public static void IsNotNull([NotNull] object? arg, string? argName) =>
    //  _ = arg ?? throw new ArgumentNullException(argName);

  }
}

尽管有空检查和[NotNull] 注释,我仍然收到CA1062 警告。有趣的是,如果我将函数移到同一个程序集中,警告就会消失。

我认为 NRT 功能适用于程序集。我在做什么/理解错了?

【问题讨论】:

  • 您可以使用null-forgiving operator 来抑制警告,例如Console.WriteLine(text!.ToUpper());
  • @ChrisPickford 是的。但我认为我所做的应该按原样工作? NRT 功能是否不能跨程序集工作?
  • 我在您的代码和Postconditions: MaybeNull and NotNull 之间看到的唯一区别是它们将字符串参数标记为可为空,即public void PrintUpper(string? text) {。可以试试吗?
  • @ChrisPickford 谢谢,是的,我也看到了 :-) 不幸的是,这并不能解决问题。

标签: c# .net-5 nullable-reference-types


【解决方案1】:

原来这是 a bug,在 roslyn 对 editorconfig 的支持中。

我的 editorconfig 有这个:

dotnet_diagnostic.CA1062.severity = warning

所以实际上这不是 c# NRT 问题。

解决方法是:

using System;
using System.Diagnostics.CodeAnalysis;

[AttributeUsage(AttributeTargets.Parameter)]
internal sealed class ValidatedNotNullAttribute : Attribute { }

namespace Common {
  public static class Guard {

    public static void IsNotNull([ValidatedNotNull][NotNull] object? arg, string? argName) =>
      _ = arg ?? throw new ArgumentNullException(argName);

  }
}

.editorconfig:

dotnet_diagnostic.CA1062.severity = warning
dotnet_code_quality.CA1062.null_check_validation_methods = Guard.IsNotNull

我假设一旦错误得到解决,我可以删除所有这些,并且由于 NRT,它会“正常工作”。

【讨论】:

    猜你喜欢
    • 2019-11-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多