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