C#スクリプト

C#スクリプト

場合によっては、プログラムの実行中にC#コードを動的に実行する必要があります。例えば、頻繁に変更される特定のアルゴリズムを設定ファイルに保存し、実行中に設定ファイルから読み込んで演算を実行するなどです。C#スクリプトを使用してこの作業を完了できます。

最后更新 2021/12/24 22: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

本文园,作者:的,転载请原文:www.cnblogs.com/zhenl/p/15714453.html

Keep Exploring

延伸阅读

更多文章
同分类 / 同标签 2026/04/22

バージョン別の. NETサポート状況(250 7 0 7更新)

仮想マシンとテストマシンを使用して、各バージョンのオペレーティングシステムの. NETサポートをテストします。オペレーティングシステムのインストール後、対応するランタイムを測定し、スターダストエージェントをパスとして実行できます。

继续阅读
同分类 / 同标签 2026/02/07

AOTの使用経験

プロジェクトの最初から、新しい機能が追加されたり、新しい構文が使用されたりするたびに、AOTリリーステストを行うという良い習慣を身につける必要があります。

继续阅读