【发布时间】: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