讲述Visual Studio中的文件嵌套(FileNesting)。

VisualStudio允许文件嵌套,例如项目文件中如果:

  <ItemGroup>
    <ClCompile Include="Hello.cpp">
      <DependentUpon>Hello.h</DependentUpon>
    </ClCompile>
  </ItemGroup>

那么在SolutionExplorer显示的时候则Hello.cpp会嵌套在Hello.h下面显示。

那怎么能达到这个效果呢?首先有一款插件叫做FileNesting,可以帮助在文件之间建立DependentUpon。可是稍微有点老了,在VisualStudio还能用,但是有时候会达不到效果。

其次,VisualStudio其实有实现FileNesting功能,而且做得相当复杂,相关的文档在于File nesting in Solution Explorer

可是自带的FileNesting功能主要是给ASP.NET使用的,参考ASP.NET Blog: File nesting in Solution Explorer

那其他类型的项目可以使用吗?其实是有办法调出相应的功能的,参考Support file nesting implemented in for dotnet core web projects #3242,在项目文件中加入:

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

也可以在Directory.Build.props加入下面内容

<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup>
  <ProjectCapability Include="DynamicDependentFile" />
  <ProjectCapability Include="DynamicFileNesting" />
</ItemGroup>
</Project>

然后在项目的根目录创建一个.filenesting.json,内容示例如下:

{
	"help": "https://go.microsoft.com/fwlink/?linkid=866610",
	"root": true,

	"dependentFileProviders": {
		"add": {
			"addedExtension": {},
		}
	}
}

然后就可以调出内置的FileNesting功能啦,在SolutionExplorer的工具栏上可以看到相应的按键。可是调出归调出,并不一定会起作用~~

参考File Nesting Not Working for all Class or Shared Library Projects #5722以及File Nesting: Investigate file nesting performance impact on non-web projects #7161,可能是因为默认开启这个功能会导致性能问题。

看似对于非ASP.NET项目,目前最好的办法还是使用FileNesting插件。

(本篇完)

2021-06-27更新

FileNesting插件只能找到项目顶层的文件,在Filter内部的文件则找不到。

(更新完)