千羽兰 發表於 2021-12-21 11:19:00

C# 脚本

<p>有些情况下,需要在程序运行期间动态执行C#代码,比如,将某些经常改变的算法保存在配置文件中,在运行期间从配置文件中读取并执行运算。这时可以使用C#脚本来完成这些工作。</p>
<p>使用C#脚本需要引用库Microsoft.CodeAnalysis.CSharp.Scripting,下面是一些示例:<br>
最基本的用法是计算算数表达式:</p>
<pre><code>Console.Write("测试基本算数表达式:(1+2)*3/4");
var res = await CSharpScript.EvaluateAsync("(1+2)*3/4");
Console.WriteLine(res);
</code></pre>
<p>如果需要使用比较复杂的函数,可以使用WithImports引入名称空间:</p>
<pre><code>Console.WriteLine("测试Math函数:Sqrt(2)");
res = await CSharpScript.EvaluateAsync("Sqrt(2)", ScriptOptions.Default.WithImports("System.Math"));
Console.WriteLine(res);
</code></pre>
<p>不仅是计算函数,其它函数比如IO,也是可以的:</p>
<pre><code>Console.WriteLine(@"测试输入输出函数:Directory.GetCurrentDirectory()");
res = await CSharpScript.EvaluateAsync("Directory.GetCurrentDirectory()",
   ScriptOptions.Default.WithImports("System.IO"));
Console.WriteLine(res);
</code></pre>
<p>字符串函数可以直接调用:</p>
<pre><code>Console.WriteLine(@"测试字符串函数:""Hello"".Length");
res = await CSharpScript.EvaluateAsync(@"""Hello"".Length");
Console.WriteLine(res);
</code></pre>
<p>如果需要传递变量,可以将类的实例作为上下文进行传递,下面的例子中使用了Student类:</p>
<pre><code>Console.WriteLine(@"测试变量:");
var student = new Student { Height = 1.75M, Weight = 75 };
await CSharpScript.RunAsync("BMI=Weight/Height/Height", globals: student);
Console.WriteLine(student.BMI);
</code></pre>
<p>类Student:</p>
<pre><code>    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;
    }
</code></pre>
<p>重复使用的脚本可以复用:</p>
<pre><code>Console.WriteLine(@"测试脚本编译复用:");
var scriptBMI = CSharpScript.Create&lt;Decimal&gt;("Weight/Height/Height", globalsType: typeof(Student));
scriptBMI.Compile();

Console.WriteLine((await scriptBMI.RunAsync(new Student { Height = 1.72M, Weight = 65 })).ReturnValue);
</code></pre>
<p>在脚本中也可以定义函数:</p>
<pre><code>Console.WriteLine(@"测试脚本中定义函数:");
string script1 = "decimal Bmi(decimal w,decimal h) { return w/h/h; } return Bmi(Weight,Height);";

var result = await CSharpScript.EvaluateAsync&lt;decimal&gt;(script1, globals: student);
Console.WriteLine(result);
</code></pre>
<p>在脚本中也可以定义变量:</p>
<pre><code>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);
</code></pre>
<p>完整的实例可以从github下载:https://github.com/zhenl/CSharpScriptDemo</p>


</div>
<div id="MySignature" role="contentinfo">
    <p>本文来自博客园,作者:寻找无名的特质,转载请注明原文链接:https://www.cnblogs.com/zhenl/p/15714453.html</p><br><br>
来源:https://www.cnblogs.com/zhenl/p/15714453.html
頁: [1]
查看完整版本: C# 脚本