C#スクリプトのすゝめ(.csx)

コンピュータ

C#スクリプトはコンパイラ型の言語であるC#をスクリプト言語の様に扱うことが出来ます。

導入

次のコマンドを Windows ターミナル(PowerShell / cmd / Windows Terminal) で実行してください。

dotnet tool install -g dotnet-script

バージョンの確認

dotnet script --version
# 1.6.0

スクリプトの実行方法

拡張子

拡張子は.csxになります。

サンプルスクリプト

ファイル名:hello.csx”

#r "System.dll"

Console.WriteLine("Hello C# Script");

#r "System.dll"は本来不要ですが、vscodeでConsole.WriteLine()が見つからないとエラーが出ていましたので回避用のおまじないです。

実行

dotnet-script hello.csx

# 結果
# Hello C# Script

C#スクリプト向けラッパーライブラリ

C#ですので.NETライブラリを呼び出してプログラミングをすることが出来るわけですが、メソッド名が長めなのでラッパーライブラリを作ります。

Read と Echo

まずはファイルを読み込んで表示するだけの基本関数を定義します。

ライブラリ
ファイル名:ScriptExt.csx

#r "System.dll"

using System;
using System.IO;

public static string Read(this string path) => File.ReadAllText(path);
public static string WriteTo(this string content, string path)
{
    File.WriteAllText(path, content);
    return content;
}

public static string Echo(this string text)
{
    Console.WriteLine(text);
    return text;
}

public static string Replace(this string text, string oldVal, string newVal)
    => text.Replace(oldVal, newVal);

public static string Trim(this string text) => text.Trim();

ライブラリを使うサンプルコード
ファイル名:ScriptExtSample.csx

#load "ScriptExt.csx"

Read("hello.csx")
    .Replace("Script", "ScriptExt")
    .Trim()
    .WriteTo("output.txt")
    .Echo();

実行&結果

dotnet-script scriptExtSample.csx

# 結果
# #r "System.dll"
# 
# Console.WriteLine("Hello C# ScriptExt");

#load "スクリプト名.csx"で他のスクリプトを参照。
・拡張メソッドを使ってメッソッドチェーンにしていますが、csxの場合トップレベルステートメントに書く必要が有るようです。

コメント