6

我想有条件地编译一个不包括特定类的项目。可能吗?

更新:

基本上我正在寻找的是通过不编译特定类(存储在单独的 .cs 文件中)及其所有依赖项来通过命令行指令减小生成的 .xap 文件的大小。

这是MSDN建议手动执行此操作的方式。如果有办法以自动化的方式有条件地做到这一点,那将是一个完美的解决方案。

4

3 回答 3

7

项目文件ProjectName.cproj是一个包含项目属性和编译器指令的纯 xml 文件。要包含的文件列在<ItemGroup>...</ItemGroup>标签之间。可以有一个或多个这样<ItemGroup>的列表。因此,您要做的就是将要有条件地编译的文件放入一个单独的文件中,<ItemGroup>然后添加一个条件作为属性:

<ItemGroup Condition=" '$(BUILD)' == 'IMAGE' ">
    <Compile Include="PngEncoder\Adler32.cs" />
    <Compile Include="PngEncoder\CRC32.cs" />
    <Compile Include="PngEncoder\Deflater.cs" />
    <Compile Include="PngEncoder\DeflaterConstants.cs" />
    <Compile Include="PngEncoder\DeflaterEngine.cs" />
    <Compile Include="PngEncoder\DeflaterHuffman.cs" />
    <Compile Include="PngEncoder\DeflaterOutputStream.cs" />
    <Compile Include="PngEncoder\DeflaterPending.cs" />
    <Compile Include="PngEncoder\IChecksum.cs" />
    <Compile Include="PngEncoder\PendingBuffer.cs" />
    <Compile Include="PngEncoder\PngEncoder.cs" />
</ItemGroup>

BUILD现在这组文件只有在定义了名称和值的属性时才会包括在内"IMAGE"。可以在项目文件本身中定义属性:

<PropertyGroup>
    <Configuration Condition=" '$(Configuration)' == '' ">Release</Configuration>
    <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
    <ProductVersion>8.0.50727</ProductVersion>
    ...
</PropertyGroup>

或者从命令行传入:

msbuild ProjectName.cproj /p:BUILD=IMAGE

msbuild.exe带有.NET 框架

于 2013-01-06T14:05:31.120 回答
5

你可以使用ConditionalAttribute这个:

向编译器指示应忽略方法调用或属性,除非定义了指定的条件编译符号。

[Conditional("SomeCondition")]
public void WillCompileOnlyIfSomeConditionIsDefined()
{
}

另一种方法是使用预处理器指令

#if !SomeCondition
  // will only compile if SomeCondition is false
#endif
于 2013-01-05T20:05:07.513 回答
1

在带有 Visual Studio Online 的构建中,ItemGroup 元素中的条件属性将被忽略。

如此处所述,支持使用When/Choose/Otherwise属性。

 <Choose>
     <When Condition="'$(Configuration)' == 'Debug With Project References'">
       <ItemGroup>
        <ProjectReference Include="..\SomeProject\SomeProject.csproj">
        <Project>{6CA7AB2C-2D8D-422A-9FD4-2992BE62720A}</Project>
        <Name>SomeProject</Name>
      </ProjectReference>
    </ItemGroup>
  </When>
      <Otherwise>
        <ItemGroup>
           <Reference Include="SomeProject">
             <HintPath>..\Libraries\SomeProject.dll</HintPath>
           </Reference>
         </ItemGroup>
       </Otherwise>
    </Choose>
于 2016-11-08T23:55:34.703 回答