Msbuild 如果我有对某个dll的引用,则在csproj文件中定义常量

Msbuild 如果我有对某个dll的引用,则在csproj文件中定义常量,msbuild,msbuild-task,msbuild-4.0,Msbuild,Msbuild Task,Msbuild 4.0,我想用一个条件定义msbuild常量: <DefineConstants Condition="if have a reference to MyTest.dll">TEST</DefineConstants> <ItemGroup> <Reference Include="System" /> <Reference Include="System.Core" /> <Referen

我想用一个条件定义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>
测试
如何操作?

有关如何使用“我的项目组是否包含项目X?”之类的条件的示例,请参见。然而,正如前面提到的,当在全局范围内调用时,它不起作用,它必须在一个目标内完成。因此,您必须添加此类目标并使其在构建开始前自动运行:

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

试验

这是可能的,但您需要绕过限制,即目标之外的
PropertyGroup
ItemGroup
元素上的条件表达式在访问项元数据时有一些限制

只需将项目组连接到标量属性,即可利用
ItemGroup
扩展。在这里,我基本上是将
\u 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>

美元(定义常量)@(_DefineConstants)
这将打印
“测试”


谢谢您的回答,我看到它在msbuild目标内部工作。但我需要它在csproj文件中工作。它对我不起作用。为什么你认为你需要它在目标之外?此外,不是100%确定,但我认为这根本不可能。