The annotation for nullable reference types should only be used in code within a '#nullable' context

前端 未结 2 1354
醉梦人生
醉梦人生 2021-01-30 12:11

Just downloaded VS2019 and created a console app to try out the new C# 8 null reference types. Switched the project to build with lang ver C# 8 (currently showing as beta)

2条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-30 13:06

    I got this same error too, and I spent a few days fighting it, for a reason not described by the other answers: There are special (undocumented?) rules in the Roslyn C# compiler for generated code that uses the nullable feature, and until I upgraded Visual Studio 2019 to the latest version (16.4+), the error message was exactly the same unhelpful message as above — despite having enabled in my project file.

    But in the latest versions of Visual Studio 2019, they've upgraded the error message to this:

    warning CS8669: The annotation for nullable reference types should only be used in code within a ‘#nullable’ annotations context. Auto-generated code requires an explicit ‘#nullable’ directive in source.

    (Emphasis added to the newly-added part of the error message.)

    So if you're seeing this error message in any .generated.cs files you're emitting, those files need to have #nullable enable added to them explicitly — Roslyn apparently always ignores the project-level enable setting for generated code.

提交回复
热议问题