.NET file-based app 多文件支持
.NET file-based app 多文件支持
Intro
.NET 11 Preview 3 中实现支持了文件程序的多文件支持,文件程序的实用性进一步获得了增强,我们现在可以将一些希望公用的一些逻辑写到单独的帮助类文件中以实现复用,在主文件中使用 #: include helper.cs 引入帮助类复用帮助类的方法
Sample
文件结构如下:
- Directory.Build.props- helper.cs- hello.cs
目前多文件的支持还处于实验阶段,需要显式地声明属性 <ExperimentalFileBasedProgramEnableIncludeDirective>true</ExperimentalFileBasedProgramEnableIncludeDirective>,后续的版本会去掉这个属性,就不需要再声明了
否则得到下面的错误
This is an experimental feature, set MSBuild property 'ExperimentalFileBasedProgramEnableIncludeDirective' to 'true' to enable it.
为了使用起来方便我们将这个属性声明在 Directory.Build.props 这样我们有多个文件程序也只需要声明一次就可以了
hello.cs 文件内容如下:
public static class Helper{public static void WriteToConsole(string message) { Console.WriteLine(message); }}
hello.cs 文件内容如下:
#:include helper.csHelper.WriteToConsole("Hello, World!");
然后就可以执行 dotnet hello.cs 就会输出 Hello, World!
除了基本的包含文件我们还可以在被包含文件中添加引用
如 helper.cs 中可以再添加引用
被包含文件中添加引用的话也要添加一个属性设置
<ExperimentalFileBasedProgramEnableTransitiveDirectives>true</ExperimentalFileBasedProgramEnableTransitiveDirectives>
#:package WeihanLi.Common@1.0.88using static WeihanLi.Common.Helpers.ConsoleHelper;public static class Helper{public static void WriteToConsole(string message) { Console.WriteLine(message); }public static void Print(string message) { WriteLineWithColor(message, ConsoleColor.Green); }}
在 hello.cs 中也可以直接引用
#!/usr/bin/env dotnet#:include helper.csHelper.WriteToConsole("Hello, World!");Helper.Print("Hello, World!");
Directory.Build.props
<Project> <PropertyGroup> <ExperimentalFileBasedProgramEnableIncludeDirective>true</ExperimentalFileBasedProgramEnableIncludeDirective> <ExperimentalFileBasedProgramEnableTransitiveDirectives>true</ExperimentalFileBasedProgramEnableTransitiveDirectives> </PropertyGroup></Project>
执行 dotnet hello.cs 输出结果如下:

反编译看一下会是什么样的,通过 dotnet build -v=diag hello.cs 来输出详细的一些日志,可以看到编译之后的 dll 文件

我们找到它进行一下反编译看看

从反编译结果可以看出来,最终编译成了一个项目,项目的入口文件和被引用的文件以及被引用文件的依赖一起被编译了
More
除了 include 的支持,还支持了 exclude, 就相当于 <Compile Remove/> 用的不太多就不介绍了
include 的支持在 dotnet-exec 中也得到了支持,0.36.0 版本中开始支持了 include

这一功能也会在后续的 .NET 10 SDK 更新中可用,我因为装了 VS Preview 版本,自动安装了一个 preview 版本的 SDK 10.0.300-preview.0.26177.108,这一版本也已经支持,正式版本还需要等后续的 SDK 版本更新
如下图所示,我添加了一个 global.json 来控制 SDK 的版本,可以看到后面执行的时候 SDK 版本已经从 .NET 11 preview 3 的版本变成了 10.0.300-preview 版本,但是也成功的打印出来的执行结果

References
-
• https://github.com/WeihanLi/SamplesInPractice/tree/main/net11sample/file-scripts -
• https://github.com/dotnet/sdk/pull/53775 -
• https://github.com/dotnet/sdk/pull/52347
夜雨聆风