如何在.csproj文件中使用MSBuild条件测试编译器指令?

Mik*_*ebb 13 c# msbuild compiler-directives csproj

我对.csproj文件中的函数和条件完全陌生,所以我们非常感谢所有的帮助.

我想要做的是检查当前配置中的特定编译器指令.一个例子如下:

<Choose>
    <When Condition= [current configuration has CONST-1 compiler constant defined] >
        ...
    </When>
    <When Condition= [current configuration has CONST-2 compiler constant defined] >
        ...
    </When>
</Choose>
Run Code Online (Sandbox Code Playgroud)

我不知道这是否可能.如果有更好的方法来做我要求的事情让我也知道.无论哪种方式,我想测试一个独立于配置的条件.

编辑

我真正想要的是一个我可以轻松编辑的值,最好是在Visual Studio中编辑,我也可以检查一下configuraiton.我考虑过编译器常量,因为您可以在VS的Project Properties中轻松更改它们.

Ted*_*ott 13

编译器常量被设置为属性"DefineConstants",因此您应该能够评估该属性.您的Choose语句需要在定义常量或目标内的PropertyGroup之后.

<Choose>
    <When Condition="$(DefineConstants.Contains(CONST-1))">
        ...
    </When>
    <When Condition="$(DefineConstants.Contains(CONST-2))">
        ...
    </When>
</Choose>
Run Code Online (Sandbox Code Playgroud)


小智 5

如果您使用MSBuild 4或更高版本,我建议使用正则表达式而不是String.Contains().这样做的原因是,尽管String.Contains()通常运行良好,但在某些情况下您可能会遇到问题.

例如:

考虑在代码中使用指令CONST-1和CONST-12的情况.但是,您决定仅为当前构建定义CONST-12指令.
现在Condition="$(DefineConstants.Contains('CONST-1'))"评估True即使没有定义CONST-1.

解决方案RegularExpressions.RegEx:

<When Condition="$([System.Text.RegularExpressions.Regex]::IsMatch($(DefineConstants), '^(.*;)*CONST-1(;.*)*$'))">
...
</When>
Run Code Online (Sandbox Code Playgroud)

总而言之,您可以小心确保不使用另一个子串的指令,也可以使用正则表达式而不用担心.