如何解决错误 'NotNullWhen attribute is inaccessible due to its protection level'

How to resolve error 'NotNullWhen attribute is inaccessible due to its protection level'

我有以下扩展方法,我正在尝试使用 NotNullWhen 属性修饰 out 参数 (T value)。但是,它显示错误 'NotNullWhen attribute is inaccessible due to its protection level',我不明白为什么?

    using System;
    using System.Collections.Generic;
    using System.Diagnostics.CodeAnalysis;

    internal static class Extensions
    {
        public static bool TryGetValueForAssignableType<T>(this IDictionary<Type, T> dictionary, Type key, [NotNullWhen(true)] out T value)
        {
            value = default;

            foreach (var pair in dictionary)
            {
                if (pair.Key.IsAssignableFrom(key))
                {
                    value = pair.Value;
                    return true;
                }
            }

            return false;
        }
    }

我试过将 class 访问修饰符更改为 public 但没有效果。我还为 class 库启用了 C# 8 nullable 上下文。

知道如何解决这个问题吗?

编辑:

我刚刚尝试创建一个新的 class 库,其中仅包含上述扩展 class。现在它显示“找不到名称空间名称 'NotNullWhen' 的类型(您是否缺少 using 指令或程序集引用)”。我已经包含了 using System.Diagnostics.CodeAnalysis;,但它是灰色的。 项目文件包含以下内容:

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <TargetFramework>netstandard2.0</TargetFramework>
    <Nullable>enable</Nullable>
    <LangVersion>8.0</LangVersion>
  </PropertyGroup>

</Project>

如果您打开 documentation,您会看到 NotNullWhenAttribute 适用于:

  • .NET 5.0、6.0 预览版 6
  • .NET 核心 3.1 3.0
  • .NET 标准 2.1

TBH 我也未能针对 .NET Standard 2.1 构建 lib,但您可以尝试安装 nuget,如 this one or implement this attribute yourself (like it is done in runtime),因为 AFAIK 编译器经常依赖于命名 and/or 鸭子类型。