【问题标题】:Different build action for debug and release builds in Visual StudioVisual Studio 中用于调试和发布构建的不同构建操作
【发布时间】:2025-11-26 02:35:01
【问题描述】:

我有这个实现插件架构的 C# Visual Studio 解决方案。在构建调试版本时,我希望将几个插件编译到主应用程序中。在构建发布版本时,我希望保留这些 .cs 文件。

有没有一种方法可以为插件文件指定不同的构建操作以进行调试和发布构建?我希望它在调试版本中设置为“编译”,在发布版本中设置为“无”。

【问题讨论】:

    标签: c# visual-studio-2010


    【解决方案1】:

    为此,您需要手动更改 .csproj,并在 Compile XML 元素中添加一个 Condition XML 属性,该属性对应于您仅在调试版本中需要的文件。像这样:

    <?xml version="1.0" encoding="utf-8"?>
    <Project ToolsVersion="3.5" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
      <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
          ...
      </PropertyGroup>
      <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
          ...
      </PropertyGroup>
      <ItemGroup>
        <!-- Add the Condition attribute here, on each of your debug only files
        Pick up one of the configuration definition configuration above -->
        <Compile Include="DebugOnlyClass1.cs" Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' "/>
        <!-- normal compilation -->
        <Compile Include="Class1.cs" />
        <Compile Include="Properties\AssemblyInfo.cs" />
      </ItemGroup>
         ...
    </Project>
    

    【讨论】:

      【解决方案2】:

      由于插件通常位于单独的程序集中,我将为每个插件创建一个单独的项目。

      对于项目,您可以定义是否在配置中构建:在 Visual Studio 中打开 配置管理器(菜单构建)。在左上角的组合框中选择 ReleaseDebug 配置并在列表中随意设置 build 复选框。

      编辑:否则您必须手动编辑.csproj 文件并为要排除的项目添加条件属性:

      <Compile Condition="'$(Configuration)' == 'Debug'" Include="Program.cs" />
      

      【讨论】:

      • @Simon:不,甚至没有受到启发。虽然我必须承认措辞非常相似。
      • @SimonMourier 是的,但是在您回答后 30 秒 - 我相信这是巧合。