是否有针对C#8的编译器指令或检测是否设置了<nullable>enable</nullable>
?
我只有源代码的Nuget包,可以帮助解决可为空的引用类型的故事。我想有条件地设置#nullable enable
指令(如果已设置),例如:
#ifdef ICANHASNULLABLE
#nullable enable
#endif
和
#ifdef ICANHASNULLABLE
string Foo(string? val)
#else
string Foo(string val)
#endif
我混合了使用.NET Core 2.1 SDK构建的内容,并且正在努力将其引入.NET Core 3.1,尽管速度很慢,而不仅仅是通过切换开关。该指令仅指向框架版本,而不是语言版本。
.csproj
文件中:<PropertyGroup>
<TargetFrameworks>netcoreapp2.2;netcoreapp3.1</TargetFrameworks>
</PropertyGroup>
您可以添加特定于PropertyGroup
的条件netcoreapp3.1
并定义自己的常量:
<PropertyGroup Condition="'$(TargetFramework)'=='netcoreapp3.1'"> <DefineConstants>ICANHASNULLABLE</DefineConstants> <Nullable>enable</Nullable> </PropertyGroup>
您还可以基于<Nullable>
定义指令:
<PropertyGroup Condition="'$(Nullable)'=='enable'"> <DefineConstants>ICANHASNULLABLE</DefineConstants> </PropertyGroup>
在您的代码中,您可以使用ICANHASNULLABLE
:
#if ICANHASNULLABLE void Foo(string? val) #else void Foo(string val) #endif { }
Default language version for netcoreapp 3.x is C# 8.0。因此,如果未设置PropertyGroup
,则可以将上述示例中为netcoreapp3.1
专门定义的任何LangVersion
视为特定于C#8.0。