Distinguishing Debug and Release Environments
It is well known that Debug is the compilation constant that is automatically available when developing in VS, while the code released uses Release. To create different compilation conditions in Debug and Release environments.
In a .NET Core project, you can add conditional compilation variables in the .csproj file as follows:
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
<DefineConstants>AAAA</DefineConstants>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
<DefineConstants>BBBB</DefineConstants>
</PropertyGroup>
In the code:
#if AAAA
// Your code
#elif BBBB
// Your code
#endif
It is important to note that conditional compilation constants are only effective for the current project!
Compiling Dynamic Constants
When using CI/CD tools such as Jenkins, you can dynamically configure compilation constants and pass them to all projects. First, configure the dynamic incoming constants in each project:
<PropertyGroup Condition="'$(Configuration)'=='Debug'">
<DefineConstants>$(DefineConstants)</DefineConstants>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)'=='Release'">
<DefineConstants>$(DefineConstants);</DefineConstants>
</PropertyGroup>
Then, when using the dotnet publish command, you can define custom constants using /p:DefineConstants="{variable name}"
. Note that a variable can only be used once; if used multiple times, the last one takes precedence, for example:
dotnet publish /p:DefineConstants="A" /p:DefineConstants="B"
Only B will take effect.
dotnet publish -c Release -r win-x64 /p:DefineConstants="AAA" /p:DefineConstants="TEST" --self-contained=true ;
Only TEST will take effect.
Additionally, the following practices are incorrect, and I have tested them:
/p:DefineConstants="A;B"
/p:DefineConstants="A,B"
/p:DefineConstants="`A;B`"
/p:DefineConstants="A#B"
It should be written like this!
/p:DefineConstants="A%3BB"
You must use the escape method:
| 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 |
Similarly, if you have a custom name, you can do:
<PropertyGroup Condition="'$(Configuration)'=='Release'">
<DefineConstants>$(BBB);</DefineConstants>
</PropertyGroup>
dotnet publish -c Release -r win-x64 /p:BBB="AAA%3BTEST" --self-contained=true ;
文章评论