【发布时间】:2021-06-24 09:14:34
【问题描述】:
我使用 c# 8 "Nullable Reference Types" feature 创建了一个空保护。
我将它放在Common 程序集中,并从App 程序集中调用它。两个程序集都有<Nullable>enable</Nullable>。
我的.editorconfig 有dotnet_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