AI智能
改变未来

C#通过Roslyn编写脚本


一、Roslyn添加引用集

通过

Nuget

添加

Microsoft.CodeAnalysis.CSharp

引用集,需要注意

.Net Framework4.6.1

以上版本。

添加从成功后,引入以下空间命名:

using Microsoft.CodeAnalysis;using Microsoft.CodeAnalysis.CSharp;using Microsoft.CodeAnalysis.CSharp.Scripting;using Microsoft.CodeAnalysis.CSharp.Syntax;using Microsoft.CodeAnalysis.Scripting;

二、Roslyn 基本操作

class AnalysisTest{public async void GetCurrentDateTime(){Console.WriteLine($"{DateTime.Now:HH:mm:ss:fff} 开始获取当前时间");var s4     = CSharpScript.Create(@"return DateTime.Now.ToString(""yyyy-MM-dd HH:mm:ss:fff"");", ScriptOptions.Default.WithImports("System"));var result = (await s4.RunAsync()).ReturnValue;Console.WriteLine($"{DateTime.Now:HH:mm:ss:fff} {result}");}public async void ArithmeticExpression(){string expression = "(1+2)*3/4";Console.WriteLine($"{DateTime.Now:HH:mm:ss:fff} 计算算数表达式:{expression}");var res = await CSharpScript.EvaluateAsync(expression);Console.WriteLine($"{DateTime.Now:HH:mm:ss:fff} {res}");}public async void ArithmeticExpressionParam(){Console.WriteLine($"{DateTime.Now:HH:mm:ss:fff} 测试脚本中的变量:");var script = CSharpScript.Create("int x=3;int y=1;", ScriptOptions.Default.WithImports("System.Math"));script = script.ContinueWith("int z=2;");string expression = "Sqrt(x)+y";Console.WriteLine($"{DateTime.Now:HH:mm:ss:fff} 测试Math函数:{expression}");script = script.ContinueWith("return Sqrt(x)+y-2;");Console.WriteLine($"{DateTime.Now:HH:mm:ss:fff} {(await script.RunAsync()).ReturnValue}");}public async void DefineFunction(){Console.WriteLine($"{DateTime.Now:HH:mm:ss:fff} 测试脚本中定义函数(勾股定理):");var script = CSharpScript.Create("int x=3;int y=4;", ScriptOptions.Default.WithImports("System.Math"));string script1 = "double PythagoreanTheorem(double x,double y) { return   Sqrt(Pow(x,2)+Pow(y,2)); } return PythagoreanTheorem(x,y);";script = script.ContinueWith(script1);Console.WriteLine($"{DateTime.Now:HH:mm:ss:fff} {(await script.RunAsync()).ReturnValue}");}}

三、相关资料地址

Microsoft.CodeAnalysis.CSharp Namespace | Microsoft Docs

使用C#写脚本 – SegmentFault 思否

赞(0) 打赏
未经允许不得转载:爱站程序员基地 » C#通过Roslyn编写脚本