如何使用可为空的类型引用或如何在 .NET Core 中预览时启用它

How to use type reference nullable or how to enable it on preview in .NET Core

我的问题是我一直有错误 CS8652

"C# The feature is currently in Preview and unsupported. To use Preview features, use the language version."

通过使用“?”在反序列化期间授权 属性 为 null 的类型之后(如果有帮助,我使用 JsonConvert,也许有一个参数授权某些 属性 为 null,但我真的不这么认为)

class Data
{
    String? PropertyCanBeNull { get; set; }
}

我已经尝试了几乎所有我发现的解决此错误的方法,包括以下内容: - 安装 Visual Studio 2019 预览版 - 安装 .NET SDK 进行预览(并在 CMD 中检查它是否有效) - 修改了我的项目 属性 以便它使用 .NET Core 3.0+ 版本

我也尝试过更改项目的语言版本,但对我来说似乎没用。

"When your project targets a preview framework that has a corresponding preview language version, the language version used is the preview language version."

来源:https://docs.microsoft.com/fr-fr/dotnet/csharp/language-reference/configure-language-version

德克在评论中回答 :

我还记得使用“?”在一段时间前的类型之后,但我不太确定,他们是否对其进行了任何更改以使其仅在 "preview" 或其他内容中受支持?

Nullable value types (like int?) have been in C# for a very long time. Nullable reference types (like string?) however were introduced with C# 8.

字符串在 C# 中始终 可为空。

虽然 C# 8 会 introduce the nullable reference types like public string? this is also a problem NewtonSoft's JSON Converter has had solved 一段时间:

string ignored = JsonConvert.SerializeObject(movie,
    Formatting.Indented,
    new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore });

编辑

我用 Visual Studio 回到了机器,完全更新到 Visual Studio 2019 (16.2):

如果您编辑项目解决方案

  1. 打开解决方案文件夹
  2. 右键单击解决方案并编辑

并将以下两个设置添加到 PropertyGroup 警告将消失:

<Nullable>enable</Nullable>
<LangVersion>8.0</LangVersion>