欢迎光临 Rick 's BLOG
日志首页  | C# .Net编程  | 原创作品  | 生活点滴  | C\C++相关  | 多媒体相关※ERMP  | VB相关  | 其它运维与编程  |  留言簿
C#等效于php的password_verify 和 password_hash 功能的函数实现 Jurassic [C# .Net JavaScript引擎]限制脚本执行时间,防止死循环
晴天  介绍一个C#的javascpript引擎 Jurassic
[ 发布日期:3年前 (2023-11-30) ]   [ 来自:本站原创 ] [分类:C# .Net编程]
这是一个纯.Net实现的javascpript引擎,目前支持ECMAScript 3 和 ECMAScript 5 包括 ES5 strict 模式。
ECMAScript 6的支持还在开发中,已经支持了es6的大部分特性。

性能好:它将JavaScript编译为.NET字节码(CIL),而非解释执行。这样使得它的运行性能更好;

纯.Net开发:纯.Net开发,不依赖任何第三方库,只有单个dll文件,可以完全集成到.Net框架中,可以在任何支持.Net平台执行;

使用:
1,可以直接用 NuGet 获取 Jurassic。
using Jurassic;

简单的执行js字符串
var engine = new Jurassic.ScriptEngine();
 engine.Evaluate("function main(a,b){return a+b;}");
var addResult= engine.CallGlobalFunction("main", 5, 6);//结果11


2,.Net 和 javascpript 之间交互。
暴露net的class给js
[复制到剪贴板]

using Jurassic
;
using Jurassic.Library;

public class
AppInfo : ObjectInstance
{
public
AppInfo(ScriptEngine engine)
:
base(engine)
{
// 重写name属性
this["name"] = "Test Application";

// 只读属性
this.DefineProperty("version", new PropertyDescriptor(5, PropertyAttributes.Sealed), true);
}
}

engine.SetGlobalValue("appInfo", new AppInfo(engine));
Console.WriteLine(engine.Evaluate<string>("appInfo.name + ' ' + appInfo.version")); ?>


暴露net的class的静态方法
[复制到剪贴板]

using Jurassic
;
using Jurassic.Library;

public class
Math2 : ObjectInstance
{
public
Math2(ScriptEngine engine)
:
base(engine)
{
this.PopulateFunctions();
}

[
JSFunction(Name = "log10")]
public static
double Log10(double num)
{
return
Math.Log10(num);
}
}

engine.SetGlobalValue("math2", new Math2(engine));
engine.Evaluate<double>("math2.log10(1000)"); ?>


暴露net的类实例
[复制到剪贴板]

using Jurassic
;
using Jurassic.Library;

public class
RandomConstructor : ClrFunction
{
public
RandomConstructor(ScriptEngine engine)
:
base(engine.Function.InstancePrototype, "Random", new RandomInstance(engine.Object.InstancePrototype))
{
}

[
JSConstructorFunction]
public
RandomInstance Construct(int seed)
{
return new
RandomInstance(this.InstancePrototype, seed);
}
}

public class
RandomInstance : ObjectInstance
{
private
Random random;

public
RandomInstance(ObjectInstance prototype)
:
base(prototype)
{
this.PopulateFunctions();
this.random = new Random(0);
}

public
RandomInstance(ObjectInstance prototype, int seed)
:
base(prototype)
{
this.random = new Random(seed);
}

[
JSFunction(Name = "nextDouble")]
public
double NextDouble()
{
return
this.random.NextDouble();
}
}


engine.SetGlobalValue("Random", new RandomConstructor(engine));
engine.Evaluate<double>("var rand = new Random(1000); rand.nextDouble()"); ?>

如果文章对您有帮助,给个赞赏吧!
引用通告地址 (0):
复制引用地址https://www.rickw.cn/trackback/279
复制引用地址https://www.rickw.cn/trackback/279/GBK
[ 分类:C# .Net编程  | 查看:2640 ]

暂时没有评论,快来发表一个评论吧。
发表评论
作者:   用户:[访客] 
评论:

表  情
禁止表情 | 禁止UBB | 禁止图片 | 识别链接
对不起,你没有权限上传附件!
验证:
 
PoweredBy R-Blog V1.00 © 2004-2026 WWW.RICKW.CN, Processed in second(s) , 5 queries    京ICP备17058477号-5