.NET Core腳本工具dotnet-script


什么是dotnet-script

"dotnet-script"是github上一個開源的.net core global tool, 項目地址https://github.com/filipw/dotnet-script。使用它,開發人員可以獲得在命令行直接運行C#腳本文件的能力, 且不需要創建任何項目文件。

安裝/卸載dotnet-script

.NET Core 2.1中引入了global tool, 所以你可以在命令行直接使用以下命令安裝dotnet-script

> 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及以上版本。

如果希望卸載dotnet-script, 請使用一下命令

> dotnet tool uninstall dotnet-script -g

創建第一個HelloWorld腳本

下面我們通過一個最簡單的例子,說明一下dotnet-script的使用方式。

首先我們創建一個helloworld.csx文件, 並在文件中編寫以下代碼

Console.WriteLine("Hello World!");

你沒有看錯,這個文件中只有一行代碼,沒有任何的using, namespace等代碼。

然后我們在命令行執行dotnet-script helloworld.csx, 結果如下,"Hello World!"被正確的輸出了。

C:\script>dotnet-script helloworld.csx
Hello world!

創建一個添加Nuget引用的腳本

dotnet-script可以支持使用Roslyn #r 語法(#r "nuget: {包名}, {版本號}")引用各種Nuget包。

例如,下面我們修改helloworld.csx文件, 引入Newtownsoft.Json庫,輸出一個序列化之后的字符串。

#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

EHRL

最新版本的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

編譯DLL或EXE文件

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,在命令行練習各種代碼。當然開發人員也可以使用它編寫一些簡單腳本,而不需要每次都去創建工程項目文件。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM