C# 指令碼

C# 指令碼

有些情況下,需要在程式執行期間動態執行C#程式碼,例如,將某些經常改變的演算法儲存在設定檔中,在執行期間從設定檔中讀取並執行運算。這時可以使用C#指令碼來完成這些工作。

最後更新 2021/12/24 下午10:46
寻找无名的特质
預計閱讀 3 分鐘
分類
.NET
標籤
.NET C# 指令碼

有些情況下,需要在程式執行期間動態執行 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

繼續探索

延伸閱讀

更多文章
同分類 / 同標籤 2026/2/7

AOT使用經驗總結

從專案建立伊始,就應養成良好的習慣,即只要添加了新功能或使用了較新的語法,就及時進行 AOT 發布測試。

繼續閱讀