MSBuild:如何将生成的 类 包含到编译中?

MSBuild: how to include generated classes into compilation?

我有以下 MSBuild 脚本:

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
...
    <BuildDependsOn>
      NSwag;
      $(BuildDependsOn)
    </BuildDependsOn>
    <!--<AfterTransform>NSwag</AfterTransform>-->
  </PropertyGroup>

  <ItemGroup>
...
  </ItemGroup>

  <Target Name="NSwag" BeforeTargets="BeforeBuild">
    <Message Text="Generating C# client code via NSwag" Importance="high" />

    <!-- ISSUE HERE -->
    <Copy SourceFiles="..\..\MyClient.cs" DestinationFiles="Gen\MyClient.cs" />
  </Target>

</Project>

上面的目标"NSwag"将用于代码生成工具。但是为了简化事情,我在这里只使用一个文件复制命令。

问题是在此目标中添加的 .cs 文件在 MSBuild 编译中不可见:

The type or namespace name 'MyClient' does not exist in the namespace 'MyNamespace'

注意:仅当目标文件夹中不存在该文件时才会出现此问题。

注意:我试图处理以下内容,但到目前为止没有成功:

  <Target Name="RemoveSourceCodeDuplicates" BeforeTargets="BeforeBuild;BeforeRebuild" DependsOnTargets="UpdateGeneratedFiles">
    <RemoveDuplicates Inputs="@(Compile)">
      <Output TaskParameter="Filtered" ItemName="Compile"/>
    </RemoveDuplicates>
  </Target>

  <Target Name="UpdateGeneratedFiles" BeforeTargets="BeforeBuild;BeforeRebuild" DependsOnTargets="NSwag">
    <ItemGroup>
      <Compile Include="Gen\MyClient.cs" Condition="!Exists('Gen\MyClient.cs')" />
    </ItemGroup>
  </Target>

我在这里错过了什么?

我想我找到了解决方法 - 首先检查并包含文件(UpdateGeneratedFiles 目标),然后生成它们(NSwag 目标)。请参阅以下脚本:

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
...
    <BuildDependsOn>
      NSwag;
      $(BuildDependsOn)
    </BuildDependsOn>
  </PropertyGroup>

  <Target Name="NSwag" BeforeTargets="BeforeBuild;BeforeRebuild"
          DependsOnTargets="UpdateGeneratedFiles">
    <Message Text="Generating C# client code via NSwag" Importance="high" />

    <Copy SourceFiles="..\..\MyClient.cs" DestinationFiles="Gen\MyClient.cs" />
  </Target>

  <Target Name="UpdateGeneratedFiles" BeforeTargets="BeforeBuild;BeforeRebuild" >
    <ItemGroup>
    <Compile Include="Gen\MyClient.cs" Condition="!Exists('Gen\MyClient.cs')" />
    </ItemGroup>
  </Target>

</Project>