当前位置: 首页 > 编程语言 > C#

C#分享执行Javascript脚本的方法和步骤

时间:2023-04-10 12:56:01 C#

前段时间用C#写SCXML状态机,需要解析EMCScript表达式。我用过Jint库(https://github.com/sebastienros/jint/),当时觉得用C#做数据转换不是很方便。这两天有时间关注一下,发现新的3.0版本有了很大的提升。我在这里介绍一下,供大家参考。首先安装nuget包,注意添加prerelease选项,安装最新版本,使用dotnet命令行命令如下:dotnetaddpackageJint--prerelease直接计算表达式:Console.WriteLine("直接计算表达式:(1+2)*3");varr1=e.Evaluate("(1+2)*3");控制台.WriteLine(r1);字符串操作:Console.WriteLine("字符串操作:'abc'.length");varr2=e.Evaluate("'abc'.length");控制台.WriteLine(r2);Console.WriteLine("----------------------");Console.WriteLine("字符串操作:'abc'.substr(2)");varr3=e.Evaluate("'abc'.substr(2)");控制台.WriteLine(r3);可以使用SetValue给JS变量赋值:vare2=newEngine().SetValue("x",1).SetValue("y",2);varr4=e2.Evaluate("x+y");控制台.WriteLine(r4);对象可以用于C#和JS之间的数据交换:varmyobj=newStudent{Name="张三"};Console.WriteLine(myobj.Name);变种e4=新引擎()。SetValue("student",myobj).Execute("student.Name='Lisi'");Console.WriteLine(myobj.Name);您可以将C#函数委托给JS引擎,并在JS代码中调用这些函数:Console.Write("SetCSharpfunctiontoJsengine");varengine=newEngine().SetValue("log",newAction(Console.WriteLine));engine.Execute(@"functionhello(){log('HelloWorld');};hello();");你也可以从CSharp调用JS函数:Console.WriteLine("CallJSfunctiontocalculateBMI");vare5=newEngine().Execute("functionbmi(weight,height){returnweight/height/height;}");Console.WriteLine(e5.Invoke("bmi",75,1.75));OK在JS引擎中引入CLI调用CLI中的函数:Console.WriteLine("Call.Netfunctiontowritefile");vare6=newEngine(cfg=>cfg.AllowClr());e6.Execute(@"varf=System.IO.StreamWriter('sayhello.log');f.WriteLine('Hello!');f.Dispose();");示例可以从github下载:https://github.com/zhenl/CSharpScriptDemo,本文示例在JSInCSharp项目中。C#执行Javascript脚本的方法和步骤到此结束。更多C#执行Javascript脚本的相关内容,请搜索往期文章或继续浏览以下相关文章,希望大家以后多多支持!本文收集自网络,不代表立场。如涉及侵权,请点击右侧联系管理员删除。如需转载请注明出处: