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

10

我有一些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 - Mr Qian
1个回答

17

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

首先,我认为你应该使用Directory.Build.targets而不是Directory.Build.props。正如这个文档所示,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>

它在我的端口运作正常,希望能对你有所帮助。


2
啊!起初我以为用.cs替换.Generated会导致Abc.Generated.cs变成Abc.cs.cs,但是我查了一下%(Filename)的确切返回值,它是原始文件名不包括扩展名,所以实际上是从Abc.Generated开始。现在感觉更有意义了!投票支持这个发现,同时也学到了可以使用$()语法在这里运行代码! - Mark A. Donohoe
谢谢!对于我需要的大多数事情,它都像魔法一样运行。不过我有一个问题...为什么你要使用[System.String]::Copy(%(Filename)).Replace(...)而不是只用%(Filename).Replace(...)?我知道你这样做了,但我想知道为什么。另外,有没有办法包含条件?例如,我想嵌套MyControl.Commands.cs,但是UserControl的父文件是MyControl.xaml,而自定义控件的父文件是MyControl.cs。有没有办法检查其中一个是否存在,然后使用它?(我的解决方法是使用MyControl.xaml.Commands.cs,但我讨厌它。) - Mark A. Donohoe

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接