簡體   English   中英

在編譯期間使用 MSBuild.exe 設置 Boolean 變量

[英]Set Boolean variable during the compile time using MSBuild.exe

In our C# code we have a static class with a Boolean variable IS_FEATURE_X_ENABLED and we want to be able to set this variable during the compile time, means when we call MSBuild.exe the value will be included as an argument. 例如:

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

這樣做的原因是我們希望能夠構建具有特定配置的二進制文件,但在編譯之前這個值是未知的。 If a customer wants this feature, they can select that on our web page and the binaries will be built and packaged on a Jenkins server, then a download link will be sent to the user (either per email or it will be shown on the webpage如果他們等待編譯完成)。 在這種情況下,只使用一個變量,但實際上這個數字不必有限制(因此預先構建所有可能的組合不是一個可行的選擇)。

你有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"

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM