状況によっては、プログラム実行中に動的にC#コードを実行する必要があります。例えば、頻繁に変更されるアルゴリズムを設定ファイルに保存し、実行時に設定ファイルから読み込んで計算を実行する場合などです。このような場合、C#スクリプトを使用して処理を行うことができます。
C#スクリプトを使用するには、ライブラリMicrosoft.CodeAnalysis.CSharp.Scriptingを参照する必要があります。以下にいくつかの例を示します。
最も基本的な使い方は、算術式を計算することです。
Console.Write("テスト: 基本的な算術式:(1+2)*3/4");
var res = await CSharpScript.EvaluateAsync("(1+2)*3/4");
Console.WriteLine(res);
より複雑な関数を使用する場合は、WithImportsを使用して名前空間をインポートします。
Console.WriteLine("テスト: Math関数:Sqrt(2)");
res = await CSharpScript.EvaluateAsync("Sqrt(2)", ScriptOptions.Default.WithImports("System.Math"));
Console.WriteLine(res);
計算関数だけでなく、IOなどの他の関数も使用可能です。
Console.WriteLine(@"テスト: 入出力関数:Directory.GetCurrentDirectory()");
res = await CSharpScript.EvaluateAsync("Directory.GetCurrentDirectory()",
ScriptOptions.Default.WithImports("System.IO"));
Console.WriteLine(res);
文字列関数はそのまま呼び出せます。
Console.WriteLine(@"テスト: 文字列関数:""Hello"".Length");
res = await CSharpScript.EvaluateAsync(@"""Hello"".Length");
Console.WriteLine(res);
変数を渡す必要がある場合は、クラスのインスタンスをコンテキストとして渡します。以下の例ではStudentクラスを使用しています。
Console.WriteLine(@"テスト: 変数:");
var student = new Student { Height = 1.75M, Weight = 75 };
await CSharpScript.RunAsync("BMI=Weight/Height/Height", globals: student);
Console.WriteLine(student.BMI);
クラスStudent:
public class Student
{
public Decimal Height { get; set; }
public Decimal Weight { get; set; }
public Decimal BMI { get; set; }
public string Status { get; set; } = string.Empty;
}
繰り返し使用するスクリプトは再利用できます。
Console.WriteLine(@"テスト: スクリプトのコンパイル再利用:");
var scriptBMI = CSharpScript.Create<Decimal>("Weight/Height/Height", globalsType: typeof(Student));
scriptBMI.Compile();
Console.WriteLine((await scriptBMI.RunAsync(new Student { Height = 1.72M, Weight = 65 })).ReturnValue);
スクリプト内で関数を定義することもできます。
Console.WriteLine(@"テスト: スクリプト内での関数定義:");
string script1 = "decimal Bmi(decimal w,decimal h) { return w/h/h; } return Bmi(Weight,Height);";
var result = await CSharpScript.EvaluateAsync<decimal>(script1, globals: student);
Console.WriteLine(result);
スクリプト内で変数を定義することもできます。
Console.WriteLine(@"テスト: スクリプト内の変数:");
var script = CSharpScript.Create("int x=1;");
script = script.ContinueWith("int y=1;");
script = script.ContinueWith("return x+y;");
Console.WriteLine((await script.RunAsync()).ReturnValue);
完全なサンプルは GitHub からダウンロードできます: https://github.com/zhenl/CSharpScriptDemo
本記事は博客園からのものです。著者: 寻找无名的特质。原文リンク: https://www.cnblogs.com/zhenl/p/15714453.html