【问题标题】:C# TryGet with Nullable Reference Annotation in .NET 4.x / Standard 2.0C# TryGet 在 .NET 4.x / Standard 2.0 中带有可空引用注释
【发布时间】:2021-08-23 22:37:54
【问题描述】:

在 .NET 4.x / .NET Standard 2.0 上使用 TryGet 类型的方法时,是否有办法填充可空引用安全性?

根据 Try out Nullable Reference Types | .NET Blog 看起来 NotNullWhenAttribute 在 .NET Core / .NET 5+ / .NET Standard 2.1+ 中可用,允许以下内容。

public class MyString
{
    // True when 'value' is null
    public static bool IsNullOrEmpty([NotNullWhen(false)] string? value)
    {
        ...
    }
}

public class MyVersion
{
    // If it parses successfully, the Version will not be null.
    public static bool TryParse(string? input, [NotNullWhen(true)] out Version? version)
    {
        ...
    }
}

public class MyQueue<T>
{
    // 'result' could be null if we couldn't Dequeue it.
    public bool TryDequeue([MaybeNullWhen(false)] out T result)
    {
        ...
    }
}

无论如何要在 .NET Standard 2.0 或 .NET 4.x 库中实现类似的功能?

【问题讨论】:

  • 技术上,可以找到这些属性的来源和使用它们的代码分析,并且(理论上)用于构建可以在 .NET 上运行的代码分析器固件 4.x 或 .NET 标准 2.0。在 NuGet 上的快速搜索显示人们似乎正在这样做,尽管 the first library I looked at 没有(乍一看)包含代码分析器的源 - 仅包含属性的源。不确定将分析器源移植回 .NET FW/Standard 2.0 有多么困难。

标签: c# c#-8.0 nullable-reference-types


【解决方案1】:

您可以通过多个步骤在 .NET Framework 或 .NET Standard 2.0 库中使用可为空的引用类型:

  • latest release 复制属性并使用#if 仅将属性添加到您的目标 (NullableAttributes.cs)
  • 启用可空引用类型&lt;Nullable&gt;enable&lt;/Nullable&gt;#nullable enable

.NET Framework 的 BCL 没有注释。一种解决方案是多目标项目以获取最新注释并禁用旧目标的可为空警告。

  <PropertyGroup Condition="'$(TargetFramework)' == 'netstandard2.0'">
    <NoWarn>$(NoWarn);nullable</NoWarn>
  </PropertyGroup>

我写了一篇更详细的帖子:How to use Nullable Reference Types in .NET Standard 2.0 and .NET Framework

【讨论】:

  • 会尝试一下,尽管首先通过 NuGet 库 Sean Skelly 在评论中提出。并为此大喊多目标以获得 BCL 注释!
【解决方案2】:

不幸的是,不是AFAIK,并且已经亲自尝试过,这些属性和功能仅适用于

  • .NET 5.0, 6.0, Preview 7
  • .NET Core 3.0, 3.1
  • .NET 标准 2.1

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-06-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多