【问题标题】:Automatically nest files in .csproj class libary (DependentUpon)在 .csproj 类库中自动嵌套文件 (DependentUpon)
【发布时间】:2020-07-22 17:05:57
【问题描述】:

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

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

版本

  • .NET Core 3.1
  • Visual Studio 2019 (16.5.3)

尝试 A 失败:

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

尝试 B 失败:

<Compile Update="**\*Generated.cs">
  <DependentUpon>%(Filename)</DependentUpon>
</Compile>

尝试 C 失败:

<Compile Update="**\*Generated.cs">
  <DependentUpon>%(Filename).cs</DependentUpon>
</Compile>

上面的方法也试过了:

<ItemGroup>
  <ProjectCapability Include="DynamicDependentFile" />
  <ProjectCapability Include="DynamicFileNesting" />
</ItemGroup>

【问题讨论】:

  • 请使用Directory.Build.targets 而不是Directory.Build.props

标签: c# visual-studio .net-core msbuild csproj


【解决方案1】:

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

首先,我认为您应该使用Directory.Build.targets 而不是Directory.Build.props。正如this document 所示,Directory.Build.props 很早就在 Microsoft.Common.props 中被导入,并且 Itemgroup 元素在 MSBuild 属性之后被识别,因此当您在 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>

它对我有用,希望它可以帮助你。

【讨论】:

  • 啊啊啊!起初我以为用.cs 替换.Generated 会导致Abc.Generated.cs 被更改为Abc.cs.cs 但后来我查了一下%(Filename) 返回的确切内容,它是原始文件名没有扩展名,所以它实际上是从Abc.Generated 开始的。现在更有意义了!投票也是为了学习你可以用$()语法在这里运行代码!
  • 谢谢!对于我需要的大多数东西,它就像一个魅力。问题虽然......为什么你必须使用[System.String]::Copy(%(Filename)).Replace(...) 而不仅仅是%(Filename).Replace(...) 我知道你这样做,但我想知道为什么。其次,有没有办法包含条件?例如,我想嵌套MyControl.Commands.cs,但UserControl 的父文件是MyControl.xaml,而对于自定义控件,它是MyControl.cs。有没有办法检查一个或另一个是否存在,然后使用它? (我的解决方法是使用MyControl.xaml.Commands.cs,但我讨厌它。)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-11-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-07-27
相关资源
最近更新 更多