gpt4 book ai didi

c# - 在编译期间使用 MSBuild.exe 设置 bool 变量

转载 作者:行者123 更新时间:2023-12-04 03:25:40 24 4
gpt4 key购买 nike

在我们的 C# 代码中,我们有一个带有 bool 变量 IS_FEATURE_X_ENABLED 的静态类,我们希望能够在编译期间设置此变量,这意味着当我们调用 MSBuild.exe 时,该值将为作为论据包括在内。例如:

MSBuild.exe FeatureFlexibleApp.sln -p:IsFeatureXEnabled=true

这样做的原因是我们希望能够构建具有特定配置的二进制文件,但在编译之前这个值是未知的。如果客户想要此功能,他们可以在我们的网页上选择,二进制文件将在 Jenkins 服务器上构建和打包,然后将向用户发送下载链接(通过电子邮件或在网页上显示)如果他们等待编译完成)。在这种情况下,只使用了一个变量,但实际上这个数字不必有限制(因此预先构建所有可能的组合不是一个可行的选择)。

最佳答案

您有 2 个选择。

首先是使用此 MSBuild 属性来控制是否定义特定的预处理器符号,然后在您的 C# 代码中使用 #if:

<PropertyGroup>
<DefineConstants Condition="'$(IsFeatureXEnabled)' == 'true'">$(DefineConstants);IS_FEATURE_X_ENABLED</DefineConstants>
</PropertyGroup>

然后:

#if IS_FEATURE_X_ENABLED
// Code compiled only if feature X is enabled
#endif

但是,如果您沿着这条路走下去,则更容易废弃 csproj 中的样板,并直接从命令行设置 DefineConstants:

MSBuild.exe FeatureFlexibleApp.sln -p:DefineConstants=IS_FEATURE_X_ENABLED

另一种是使用MSBuild属性的值编写一个程序集级别的属性,然后在运行时用代码读取这个属性。

在程序集的不同构建之间唯一发生变化的是这些程序集级属性的值:其他所有内容都在运行时确定,这可能是也可能不是您想要的。但是,这确实意味着您可以将任何旧字符串传递到您的代码中,而不仅仅是二进制启用/未启用。

<ItemGroup>
<AssemblyAttribute Include="Namespace.Of.Your.ConfigurationAttribute">
<IsFeatureXEnabled>$(IsFeatureXEnabled)</IsFeatureXEnabled>
</AssemblyAttribute>
</ItemGroup>
[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = false)]
internal class ConfigurationAttribute : Attribute
{
public string IsFeatureXEnabled { get; set; }
}

...

bool isFeatureXEnabled = typeof(...).Assembly
.GetCustomAttribute<ConfigurationAttribute>().IsFeatureXEnabled == "true"

关于c# - 在编译期间使用 MSBuild.exe 设置 bool 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67637688/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com