如何在.Net Core中使用自定义预处理指令

27

我尝试在 .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

根据 dotnet --version,我正在使用工具版本1.0.1。

有没有人知道如何使用命令行正确设置 .net core 的指令?

3个回答

29

你需要设置的是 /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文件中添加以下内容


An easier solution would create a configuration called Mac and in your csproj have.
  <PropertyGroup Condition="'$(Configuration)'=='Mac'">
    <DefineConstants>TRACE;NETCOREAPP1_1;MAC</DefineConstants>
  </PropertyGroup>

然后从命令行中,您只需要执行以下操作:

dotnet msbuild /p:Configuration=Mac

嗯... DefineConstants 似乎没有起到作用。而且,当我在值中放置多个时,会出现错误 MSB1006,指出该属性无效。 - John Koerner
3
好的,我发现它不喜欢常量周围的引号。如果我不使用引号,那么DefineConstants就可以工作了。 - John Koerner

15
如果您想要自定义配置开关,而不影响其他设置(像Debug / Release这样的“配置”),则可以定义任何其他属性并在构建中使用它。
例如,对于dotnet build /p:IsMac=true,您可以将以下内容添加到csproj文件中(请注意,run可能无法正确传递属性,但在执行清除操作后,IsMac=true dotnet run将起作用):
<PropertyGroup>
  <DefineConstants Condition=" '$(IsMac)' == 'true' ">$(DefineConstants);MAC</DefineConstants>
</PropertyGroup>

如果你想更进一步并自动检测是否在Mac上进行构建,可以使用msbuild属性函数来评估你正在构建的操作系统。请注意,这仅适用于msbuild的 .net core 变体(dotnet msbuild)。有关支持的详细信息,请参见this PR
<PropertyGroup>
  <IsMac>$([System.Runtime.InteropServices.RuntimeInformation]::IsOSPlatform($([System.Runtime.InteropServices.OSPlatform]::get_OSX())))</IsMac>
  <DefineConstants Condition=" '$(IsMac)' == 'true' ">$(DefineConstants);MAC</DefineConstants>
</PropertyGroup>

0
构建在 Martin 的回答之上,你可以将它简化为这样:
<PropertyGroup>
    <!-- Define additional preprocessor directives -->
    <DefineConstants Condition="'$(DefineAdditionalConstants)' != ''">$(DefineConstants);$(DefineAdditionalConstants)</DefineConstants>
</PropertyGroup>

然后在命令行中,您可以执行以下操作:

dotnet build '-p:DefineAdditionalConstants=CONSTANT'


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接