.NET file-based app 多文件支持

张开发
2026/4/21 6:33:21 15 分钟阅读

分享文章

.NET file-based app 多文件支持
.NET file-based app 多文件支持Intro.NET 11 Preview 3 中实现支持了文件程序的多文件支持文件程序的实用性进一步获得了增强我们现在可以将一些希望公用的一些逻辑写到单独的帮助类文件中以实现复用在主文件中使用#: include helper.cs引入帮助类复用帮助类的方法Sample文件结构如下- Directory.Build.props - helper.cs - hello.cs目前多文件的支持还处于实验阶段需要显式地声明属性ExperimentalFileBasedProgramEnableIncludeDirectivetrue/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.cs Helper.WriteToConsole(Hello, World!);然后就可以执行dotnet hello.cs就会输出Hello, World!除了基本的包含文件我们还可以在被包含文件中添加引用如helper.cs中可以再添加引用被包含文件中添加引用的话也要添加一个属性设置ExperimentalFileBasedProgramEnableTransitiveDirectivestrue/ExperimentalFileBasedProgramEnableTransitiveDirectives#:package WeihanLi.Common1.0.88 using 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.cs Helper.WriteToConsole(Hello, World!); Helper.Print(Hello, World!);Directory.Build.propsProject PropertyGroup ExperimentalFileBasedProgramEnableIncludeDirectivetrue/ExperimentalFileBasedProgramEnableIncludeDirective ExperimentalFileBasedProgramEnableTransitiveDirectivestrue/ExperimentalFileBasedProgramEnableTransitiveDirectives /PropertyGroup /Project执行dotnet hello.cs输出结果如下dotnet hello.cs反编译看一下会是什么样的通过dotnet build -vdiag hello.cs来输出详细的一些日志可以看到编译之后的 dll 文件dotnet build我们找到它进行一下反编译看看decompile从反编译结果可以看出来最终编译成了一个项目项目的入口文件和被引用的文件以及被引用文件的依赖一起被编译了More除了include的支持还支持了exclude, 就相当于Compile Remove/用的不太多就不介绍了include的支持在 dotnet-exec 中也得到了支持0.36.0 版本中开始支持了 includedotnet-exec multiple files这一功能也会在后续的 .NET 10 SDK 更新中可用我因为装了 VS Preview 版本自动安装了一个 preview 版本的 SDK10.0.300-preview.0.26177.108这一版本也已经支持正式版本还需要等后续的 SDK 版本更新如下图所示我添加了一个global.json来控制 SDK 的版本可以看到后面执行的时候 SDK 版本已经从 .NET 11 preview 3 的版本变成了10.0.300-preview版本但是也成功的打印出来的执行结果.NET 10 Sdk SupportReferences• https://github.com/WeihanLi/SamplesInPractice/tree/main/net11sample/file-scripts• https://github.com/dotnet/sdk/pull/53775• https://github.com/dotnet/sdk/pull/52347

更多文章