【问题标题】:DefineConstants in csproj file if I have a reference to some dll如果我引用了某些 dll,则在 csproj 文件中定义常量
【发布时间】:2018-06-05 07:18:31
【问题描述】:

我想用一个条件定义 msbuild 常量:

<DefineConstants Condition="if have a reference to MyTest.dll">TEST</DefineConstants>


    <ItemGroup>
      <Reference Include="System" />
      <Reference Include="System.Core" />
      <Reference Include="MyTest.dll" />
   </ItemGroup>

我该怎么做?

【问题讨论】:

    标签: msbuild msbuild-task msbuild-4.0


    【解决方案1】:

    请参阅 this question 示例,了解如何使用“我的项目组是否包含项目 X?”之类的条件。但是,正如在全局范围内调用时所指出的那样,它必须在 Target 内完成。所以你必须添加这样的 Target 并让它在构建开始之前自动运行:

    <Target Name="AdjustDefineConstants" BeforeTargets="PrepareForBuild">
      <PropertyGroup>
        <DefineConstants Condition="'%(Reference.Identity)' == 'Mytest.dll'">TEST</DefineConstants>
      </PropertyGroup>
      <Message Text="DefineConstants is now $(DefineConstants)"/>
    </Target>
    

    【讨论】:

    • 感谢您的回答,我看到它在 msbuild 目标中工作。但我需要它在 csproj 文件中工作。它不适合我。
    • 为什么您认为您需要在 Target 之外使用它?此外,不是 100% 确定,但我认为这根本不可能。
    【解决方案2】:

    这是可能的,但您需要解决以下限制:目标之外的PropertyGroupItemGroup 元素上的条件表达式在访问项目元数据时有一些限制。

    您可以通过简单地将项目组连接到标量属性来利用 ItemGroup 扩展。这里我基本上把_DefineConstants粘在DefineConstants的背面

    <?xml version="1.0" encoding="utf-8"?>
    <Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
    
      <ItemGroup>
        <Reference Include="MyTest.dll" />
      </ItemGroup>
    
      <ItemGroup Condition="@(Reference->AnyHaveMetadataValue('Identity', 'MyTest.dll'))">
        <_DefineConstants Include="Test" />
      </ItemGroup>  
    
      <PropertyGroup>
        <DefineConstants>$(DefineConstants);@(_DefineConstants)</DefineConstants>
      </PropertyGroup>
    
      <Target Name="Build">  
        <Message Text="DefineConstants: $(DefineConstants)" />
      </Target>
    
    </Project>
    

    这将打印";Test"

    【讨论】:

      猜你喜欢
      • 2011-12-11
      • 1970-01-01
      • 1970-01-01
      • 2012-02-09
      • 2014-06-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多