在 .csproj 类库中自动嵌套文件 (DependentUpon)

Cra*_*ham 2 c# msbuild csproj visual-studio .net-core

我有许多正在生成的 C# 文件。我希望它们自动嵌套在 Visual Studio 解决方案资源管理器中匹配的 C# 文件下。例如,Foo.Generated.cs 和 Bar.Generated.cs 将分别嵌套在 Foo.cs 和 Bar.cs 下。

如果可能,我希望能够在我的 Directory.Build.props 文件中管理它,因此我的解决方案中的所有类库都将具有相同的行为。

版本

  • .NET 核心 3.1
  • Visual Studio 2019 (16.5.3)

失败的尝试 A:

<Compile Update="**\*Generated.cs">
  <DependentUpon>$([System.String]::Copy(%(Filename)).Replace('.Generated', '.cs'))</DependentUpon>
</Compile>
Run Code Online (Sandbox Code Playgroud)

失败的尝试 B:

<Compile Update="**\*Generated.cs">
  <DependentUpon>%(Filename)</DependentUpon>
</Compile>
Run Code Online (Sandbox Code Playgroud)

失败的尝试 C:

<Compile Update="**\*Generated.cs">
  <DependentUpon>%(Filename).cs</DependentUpon>
</Compile>
Run Code Online (Sandbox Code Playgroud)

上述方法也已尝试过:

<ItemGroup>
  <ProjectCapability Include="DynamicDependentFile" />
  <ProjectCapability Include="DynamicFileNesting" />
</ItemGroup>
Run Code Online (Sandbox Code Playgroud)

Mr *_*ian 5

如果可能,我希望能够在我的 Directory.Build.props 文件中管理它,因此我的解决方案中的所有类库都将具有相同的行为。

首先,我认为你应该使用Directory.Build.targets而不是Directory.Build.props. 正如本文档所示,Directory.Build.props在 Microsoft.Common.props 中很早就导入了,并且 Itemgroup 元素在 MSBuild Properties 之后被识别,因此当您在 中添加项目时Directory.Build.props,MSBuild 将无法识别这些元素。

但是Directory.Build.targets很晚才导入,MSBuild 那时已经开始识别它们,您可以使用它添加可以在该文件中识别的任何项目。

解决方案

1)将您的文件更改为Directory.Build.targets

2)在其中添加这些(你的):

<Compile Update="**\*Generated.cs">
  <DependentUpon>$([System.String]::Copy(%(Filename)).Replace('.Generated', '.cs'))</DependentUpon>
</Compile>
Run Code Online (Sandbox Code Playgroud)

它在我身边工作,希望它可以帮助你。

  • 啊啊啊!起初我以为用“.cs”替换“.Generate”会导致“Abc.Generate.cs”更改为“Abc.cs.cs”,但后来我准确地查找了“%(Filename)”返回的内容,并且它是原始文件名*不带*扩展名,因此它实际上以“Abc.Generate”开头。现在变得更有意义了!对此进行投票也是为了学习您实际上可以使用“$()”语法在这里运行代码! (2认同)