我试图在.Net核心中使用预处理程序指令,但我无法确定获取指令的正确方法:
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
我根据dotnet --version
有谁知道如何使用.net核心从命令行正确设置指令?
答案 0 :(得分:8)
你需要设置的是/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
答案 1 :(得分:7)
如果您想要不影响其他设置的自定义配置开关(“调试/发布”之类的“配置”),您可以定义任何其他属性并在构建中使用它。
E.g。对于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核心变体。有关支持的详细信息,请参阅this PR。
<PropertyGroup>
<IsMac>$([System.Runtime.InteropServices.RuntimeInformation]::IsOSPlatform($([System.Runtime.InteropServices.OSPlatform]::get_OSX())))</IsMac>
<DefineConstants Condition=" '$(IsMac)' == 'true' ">$(DefineConstants);MAC</DefineConstants>
</PropertyGroup>