dotnet-exec 0.13.0 Released
Intro
dotnet-exec
是一个 C# 程序的小工具,可以用来运行一些简单的 C# 程序而无需创建项目文件,让 C# 像 python/nodejs 一样简单,而且可以自定义项目的入口方法,支持但不限于 Main 方法。
Install/Update
dotnet-exec
是一个 dotnet tool,可以使用安装 dotnet tool 的命令来安装
安装/更新最新稳定版本:
dotnet tool update -g dotnet-execute
安装最新的 preview 版本:
dotnet tool update -g dotnet-execute --prerelease
执行 dotnet-exec -h
或者 dotnet-exec --help
即可看到一些使用说明
Features
.NET 8 support
0.13.0 版本增加了对 .NET 8 的支持,如果安装了 .NET 8 的 SDK 就可以使用 .NET 8 的一些新 API 了
例如:
dotnet-exec 'Random.Shared.GetItems(new[]{1,2,3}, 2)'
Random.GetItems
Source Generator Support
在之前的版本中,没有引入 analyzer,针对有使用 source generator 的代码会有点问题,在 0.13.0 版本中增加对 analyzer 的支持,使得我们可以使用 source generator 的代码也可以得到支持,目前仅支持 workspace compiler,对于默认的 compiler 暂时还不支持,尝试了好几种方式都不行,在 Roslyn 的仓库里提了一个 issue 也没人理我 /(ㄒoㄒ)/~~
来看一个示例吧,下面是一个使用 .NET 7 引入的针对正则表达式的一个 SourceGenerator 的功能,这里以它写了一个简单的示例
Console.WriteLine($"Hello is {RegexHelper.IsLowercase("Hello")}");
public partial class RegexHelper
{
// The Source Generator generates the code of the method at compile time
[System.Text.RegularExpressions.GeneratedRegex("^[a-z]+$")]
public static partial System.Text.RegularExpressions.Regex LowercaseLettersRegex();
public static bool IsLowercase(string value)
{
return LowercaseLettersRegex().IsMatch(value);
}
}
然后我们使用 dotnet-exec
来执行我们的代码
Enhancement
Global using
在之前的版本中我们的 global using 都是直接写的 namespace,比如 System
/System.Linq
等,如果你有注意之前我们介绍的 implicit using 部分的话会发现 SDK 默认生成的 using 都是 global::System
/global::System.Linq
这样有一个好处就是如果别人项目里有类似的子命名空间(例如:Spark.System.Linq
)的话也不会有问题,所以在新的版本中改成了使用 global::
方式
EntryPoint
在使用过程中,如果 EntryPoint
的使用还是蛮多的,每次都要输 --entry
有点长,所以加了一个别名 -e
效果等同于 --entry
Bug fix
file-local type support
在之前的版本中,对于 C# 11 的一个新特性 file-local type 默认的编译器是不支持的,workspace compiler 是支持的,在 0.13.0 版本中修复了默认编译器的支持
More
如果你在使用 docker 方式使用,新版本的 docker 镜像也更新为使用 .NET 8 作为基础镜像了~
顺便提一句不相关的话题,.NET 8 Preview 1 里 Json UnmappedError 错误信息的 BUG 已经修复了
References
https://github.com/WeihanLi/dotnet-exec
https://www.nuget.org/packages/dotnet-execute/
https://hub.docker.com/r/weihanli/dotnet-exec
https://github.com/WeihanLi/dotnet-exec/compare/0.12.0...0.13.0
https://github.com/dotnet/roslyn/issues/67296