在 MSBuild 中传递变量的不同方法

我对 MS Build 相当陌生,并且一直在回顾 VisualStudio 附带的许多内置目标文件。我见过变量以几种不同的方式传递,但不太确定它们之间的区别:

$(...)
@(...)
%(...)
9641 次浏览

Dollar - $(MyProp): Allows you to reference values specified within PropertyGroups.

At Sign - @(CodeFile): Allows you to reference lists of items specified within ItemGroups.

Percent - %(CodeFile.BatchNum): Allows you to reference batched ItemGroup values using metadata. This is a bit more complicated, so definitely review the documentation for more info.

Take a look at each link for more detailed info on how these are used. Good luck -- hope this helps!

  • $(...)is used to access Property value (More info on Property element)

    <PropertyGroup>
    <Configuration>Debug</Configuration>
    </PropertyGroup>
    
    
    <Message Text="Configuration = $(Configuration)"/>
    
  • @(...) is used to access Item value (More info on Item element)

    <ItemGroup>
    <Reference Include="System.Data"/>
    <Reference Include="System.Web.*"/>
    </ItemGroup>
    
    
    <Message Text="References = @(Reference)"/>
    
  • %(...) is used to acces Item Metadata value (More info on Item Metadata). It's also used to do batching.

    <ItemGroup>
    <Compile Include="Account\ChangePassword.aspx.cs">
    <DependentUpon>ChangePassword.aspx</DependentUpon>
    <SubType>ASPXCodeBehind</SubType>
    <Compile/>
    </ItemGroup>
    
    
    <Message Text="Element @(Compile) of subtype %(SubType) and depend of %(DependentUpon)"/>
    

A bit of extension on the % (item metadata), there is also the Well-known item metadata: https://learn.microsoft.com/en-us/visualstudio/msbuild/msbuild-well-known-item-metadata?view=vs-2017

E.g. ModifiedTime:

  <ItemGroup>
<IntermediateAssembly Include="$(IntermediateOutputPath)$(TargetName)$(TargetExt)"/>
</ItemGroup>


<PropertyGroup>
<_AssemblyTimestampBeforeCompile>%(IntermediateAssembly.ModifiedTime)</_AssemblyTimestampBeforeCompile>
</PropertyGroup>