dotnet-script
"dotnet-script"是github上一个开源的.net core global tool, 项目地址https://github.com/filipw/dotnet-script。使用它,开发人员能够得到在命令行直接运行C#脚本文件的能力, 且不须要建立任何项目文件。git
dotnet-script
.NET Core 2.1中引入了global tool, 因此你能够在命令行直接使用如下命令安装dotnet-script
。github
> dotnet tool install -g dotnet-script You can invoke the tool using the following command: dotnet-script Tool 'dotnet-script' (version '0.26.1') was successfully installed.
Tips: 为了使用global tool, 请安装.NET Core SDK 2.1.300及以上版本。c#
若是但愿卸载dotnet-script
, 请使用一下命令app
> dotnet tool uninstall dotnet-script -g
下面咱们经过一个最简单的例子,说明一下dotnet-script
的使用方式。oop
首先咱们建立一个helloworld.csx文件, 并在文件中编写如下代码学习
Console.WriteLine("Hello World!");
你没有看错,这个文件中只有一行代码,没有任何的using, namespace等代码。lua
而后咱们在命令行执行dotnet-script helloworld.csx
, 结果以下,"Hello World!"被正确的输出了。url
C:\script>dotnet-script helloworld.csx Hello world!
在dotnet-script
能够支持使用Roslyn #r 语法(#r "nuget: {包名}, {版本号}"
)引用各类Nuget包。spa
例如,下面咱们修改helloworld.csx文件, 引入Newtownsoft.Json
库,输出一个序列化以后的字符串。.net
#r "nuget: Newtonsoft.Json, 11.0.2" using Newtonsoft.Json; Console.WriteLine(JsonConvert.SerializeObject(new { Message = "HelloWorld!" }));
咱们使用命令行dotnet-script helloworld.csx
从新运行helloworld.csx文件, 结果以下
C:\script>dotnet-script helloworld.csx {"Message":"HelloWorld!"}
Tips: 这里使用的是默认的Nuget源, 若是你想手动添加其余Nuget源, 运行脚本的时候,请添加
-s
参数, 例dotnet script foo.csx -s https://SomePackageSource
最新版本的dotnet-script
还支持了EHRL - Read Evaluate Print Loop, 即读取-求值-打印-循环, 这是一个在诸如Ruby、Python和Lisp这样的动态语言才有的特性。
开发人员能够在命令行使用dotnet script
命令, 进入EHRL模式, 根据你输入的表达式, dotnet-script
会帮你打印出表达式的结果。
例:
C:\script>dotnet script > 2+2 4 > var myName = "Lamond Lu"; > Console.WriteLine(myName.ToUpper()); LAMOND LU >
固然在这里你也可使用Roslyn #r 语法(#r "nuget: {包名}, {版本号}"
)引用各类Nuget包, 例:
C:\script>dotnet script > #r "nuget: Automapper, 6.1.1" > using AutoMapper; > typeof(MapperConfiguration) [AutoMapper.MapperConfiguration] >
除此以外,EHRL中,还支持多行代码模式。 dotnet-script
会帮助你检测代码块是否完整,若是当你点击回车的时候,代码块不完整,就会出现*
开头的新行。
C:\script>dotnet script > public class Foo{ * public string Name{get;set;} * } > var foo = new Foo(); >
除了运行本地脚本,最新版本的dotnet-script
还添加了运行远程脚本的功能,你须要使用http/https将你的脚本文件暴露出来。
例:
C:\script>dotnet script https://tinyurl.com/y8cda9zt Hello World
dotnet-script
还支持根据csx脚本文件,生成EXE或DLL文件。
可用的参数列表以下:
参数 | 说明 |
---|---|
-o | 指定文件生成的目录,默认当前目录 |
-n | 指定生成的文件名 |
-c | 指定使用的配置[Release/Debug] |
-d | 是否启用Debug输出 |
-r | 指定运行时 |
咱们以第一个HelloWorld.csx为例
C:\script>dotnet-script publish helloworld.csx Published C:\script\helloworld.csx (executable) to C:\script\publish\win10-x64
运行以上命令后,dotnet-script
会使用SCD(Self-contained deployments)的方式生成script.dll和script.exe及运行它所须要的全部基础库。
dotnet-script
做为了一个global tool, 至关简单易用, 使用它,你能够像学习Python同样学习.NET Core,在命令行练习各类代码。固然开发人员也可使用它编写一些简单脚本,而不须要每次都去建立工程项目文件。