ie.*_*ie. 10 c# msbuild preprocessor-directive dotnet-cli
我创建了一个针对两个框架(.net core 2.2 和 .net core 3.0)并使用目标框架符号(NETCOREAPP2_2 和 NETCOREAPP3_0)的小型应用程序。
项目文件非常简单,如下所示:
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFrameworks>netcoreapp3.0;netcoreapp2.2</TargetFrameworks>
<OutputType>Exe</OutputType>
</PropertyGroup>
</Project>
Run Code Online (Sandbox Code Playgroud)
程序代码可能再简单不过了:
public class MyClass
{
static void Main()
{
#if NETCOREAPP3_0
System.Console.WriteLine("Target framework: NETCOREAPP3_0");
#elif NETCOREAPP2_2
System.Console.WriteLine("Target framework: NETCOREAPP2_2");
#else
System.Console.WriteLine("Target framework: WHO KNOWS?!");
#endif
#if TEST_RUN
System.Console.WriteLine("Test mode active!");
#endif
}
}
Run Code Online (Sandbox Code Playgroud)
如果我使用常规命令而不带附加参数构建它dotnet build --no-incremental,则两个版本都会创建并按预期工作:
PS>> dotnet .\bin\Debug\netcoreapp2.2\TargetFramework.dll
Target framework: NETCOREAPP2_2
PS>> dotnet .\bin\Debug\netcoreapp3.0\TargetFramework.dll
Target framework: NETCOREAPP3_0
Run Code Online (Sandbox Code Playgroud)
在我的场景中,我需要使用附加编译符号构建两个版本TEST_RUN。所以我在构建命令中添加了额外的参数dotnet build --no-incremental -p:DefineConstants=TEST_RUN。结果我有一个应用程序,但不知道目标框架:
PS>> dotnet .\bin\Debug\netcoreapp2.2\TargetFramework.dll
Target framework: WHO KNOWS?!
Test mode active!
PS>> dotnet .\bin\Debug\netcoreapp3.0\TargetFramework.dll
Target framework: WHO KNOWS?!
Test mode active!
Run Code Online (Sandbox Code Playgroud)
我需要保留目标框架的预处理器符号,但我不知道该怎么做。有任何想法吗?
Zas*_*tai 15
您想要添加到变量,而不是设置它。
在项目文件中您将使用
<PropertyGroup>
<DefineConstants>$(DefineConstants);TEST_RUN</DefineConstants>
</PropertyGroup>
Run Code Online (Sandbox Code Playgroud)
这在命令行中可能很笨拙,所以你可以做的是使用你自己的ExtraDefineConstants属性(或任何你喜欢的名称):
<PropertyGroup>
<DefineConstants Condition=" '$(ExtraDefineConstants)' != '' ">$(DefineConstants);$(ExtraDefineConstants)</DefineConstants>
</PropertyGroup>
Run Code Online (Sandbox Code Playgroud)
然后你在命令行上传递它:dotnet build -p:ExtraDefineConstants=TEST_RUN