.NET Core 项目添加条件编译变量

2020年11月23日 4350点热度 1人点赞 3条评论
内容纲要

区分 调试和发布环境

众所周知,Debug 是在开发、在 VS 中时,自动会有的编译常量,而代码发布后则是 Release。
为了在 Debug、Release 环境下出现不同的编译条件。

.NET Core 项目添加条件编译变量,可在 .csproj 中加上

  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
        <DefineConstants>AAAA</DefineConstants>
  </PropertyGroup>
  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
        <DefineConstants>BBBB</DefineConstants>
  </PropertyGroup>

代码中:

#if AAAA
// 你的代码
#elif BBBB
// 你的代码
#endif

一定要注意,条件编译常量,只对当前项目有效!

编译动态常量

项目在使用 jenkins 等 CICD 时,可以动态配置编译常量,然后传递给所有项目。
首先每个项目中都配置动态传入常量:

    <PropertyGroup Condition="'$(Configuration'=='Debug'">
        <DefineConstants>$(DefineConstants)</DefineConstants>
    </PropertyGroup>

    <PropertyGroup Condition="'$(Configuration)'=='Release'">
        <DefineConstants>$(DefineConstants);</DefineConstants>
    </PropertyGroup>

然后在使用 dotnet publish 命令时,使用 /p:DefineConstants="{变量名称}" 自定义常量,注意,一个变量只能使用一次,多次使用以最后一个为准,如:

 dotnet publish /p:DefineConstants="A" /p:DefineConstants="B" 

只有 B 起效。

dotnet publish -c Release -r win-x64 /p:DefineConstants="AAA" /p:DefineConstants="TEST" --self-contained=true ;

只有 TEST 起效。

另外,以下做法都是错误的,我已经试过了:

/p:DefineConstants="A;B"
/p:DefineConstants="A,B"
/p:DefineConstants="<code>A;B</code>"
/p:DefineConstants="A#B" 

要这样写!

/p:DefineConstants="A%3BB"
必须使用转义方式: Character ASCII Reserved Usage
% %25 Referencing metadata
$ %24 Referencing properties
@ %40 Referencing item lists
' %27 Conditions and other expressions
; %3B List separator
? %3F Wildcard character for file names in Include and Exclude attributes
* %2A Wildcard character for use in file names in Include and Exclude attributes

同样,如果有自定义的名称,也可以:

    <PropertyGroup Condition="'$(Configuration)'=='Release'">
        <DefineConstants>$(BBB);</DefineConstants>
    </PropertyGroup>
dotnet publish -c Release -r win-x64 /p:BBB="AAA%3BTEST" --self-contained=true ;

痴者工良

高级程序员劝退师

文章评论

  • 痴者工良

    在项目编译前或编译后执行命令:

        <Target Name="ClientBuild" BeforeTargets="BeforeBuild">
            <Exec WorkingDirectory="ClientApp" Command="npm install"/>
            <Exec WorkingDirectory="ClientApp" Command="npm run build"/>
        </Target>
    

    2022年8月3日
  • 痴者工良

    利害

    2021年3月9日