我正在尝试在 .Net core 中使用预处理器指令,但我无法确定设置指令的正确方法:
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
#if MAC
Console.WriteLine("MAC");
#else
Console.WriteLine("NOT MAC");
#endif
}
我已经从命令行尝试了各种排列来使其工作,但我似乎缺少一些东西。这是我运行各种构建和运行命令时的 shell 输出:
~/dev/Temp/DirectiveTests $ dotnet msbuild /p:MAC=TRUE
Microsoft (R) Build Engine version 15.1.548.43366
Copyright (C) Microsoft Corporation. All rights reserved.
DirectiveTests -> /Users/me/dev/Temp/DirectiveTests/bin/Debug/netcoreapp1.1/DirectiveTests.dll
~/dev/Temp/DirectiveTests $ dotnet run /p:MAC=true
Hello World!
NOT MAC
~/dev/Temp/DirectiveTests $ dotnet run
Hello World!
NOT MAC
我正在使用工具版本 1.0.1 根据dotnet --version
有谁知道如何使用 .net core 从命令行正确设置指令?
您需要设置的是/p:DefineConstants=MAC
请注意,这将覆盖项目中设置的常量,例如可能设置的DEBUG
或TRACE
,因此您可能使用的完整版本将是
用于调试版本
dotnet msbuild /p:DefineConstants=TRACE;DEBUG;NETCOREAPP1_1;MAC /p:Configuration=Debug
以及发布版本
dotnet msbuild /p:DefineConstants=TRACE;NETCOREAPP1_1;MAC /p:Configuration=Release
一个更简单的解决方案是创建一个名为Mac
的配置,并在您的 csproj 中有
<PropertyGroup Condition="'$(Configuration)'=='Mac'">
<DefineConstants>TRACE;NETCOREAPP1_1;MAC</DefineConstants>
</PropertyGroup>
然后从命令行你只需要做
dotnet msbuild /p:Configuration=Mac
如果需要不影响其他设置("配置",如"调试/发布")的自定义配置开关,则可以定义任何其他属性并在生成中使用它。
例如,对于dotnet build /p:IsMac=true
,您可以将以下内容添加到csproj文件中(并不是说run
可能无法正确传递属性,尽管IsMac=true dotnet run
清理后可以正常工作):
<PropertyGroup>
<DefineConstants Condition=" '$(IsMac)' == 'true' ">$(DefineConstants);MAC</DefineConstants>
</PropertyGroup>
如果要更进一步并自动检测是否在 Mac 上构建,可以使用 msbuild 属性函数来评估正在构建的操作系统。并不是说这目前仅适用于msbuild(dotnet msbuild
)的.net core变体。有关支持的详细信息,请参阅此 PR。
<PropertyGroup>
<IsMac>$([System.Runtime.InteropServices.RuntimeInformation]::IsOSPlatform($([System.Runtime.InteropServices.OSPlatform]::get_OSX())))</IsMac>
<DefineConstants Condition=" '$(IsMac)' == 'true' ">$(DefineConstants);MAC</DefineConstants>
</PropertyGroup>
基于马丁的回答,你可以像这样简单:
<PropertyGroup>
<!-- Define additional preprocessor directives -->
<DefineConstants Condition="'$(DefineAdditionalConstants)' != ''">$(DefineConstants);$(DefineAdditionalConstants)</DefineConstants>
</PropertyGroup>
然后在命令行上,您可以执行以下操作:
dotnet build '-p:DefineAdditionalConstants=CONSTANT'