jint - 金特。如何设置类的属性或调用方法?
问题描述
使用 Jint,我如何设置 javascript 类实例的属性(或调用方法)?
例如,如果我这样做:
var o = new Jint.Engine().Evaluate(@"
class MyClass {
constructor() {
this.myProperty = null;
}
}
const o = new MyClass;
return o;
");
然后如何设置返回o
对象的 myProperty 值?
这是使用 Jint v3。
解决方案
要访问从 Jint 返回的内容,您可以通过调用将其转换为对象并将ToObject()
其声明为动态的,以便您可以使用任意属性:
dynamic o = new Jint.Engine().Evaluate(
@"
class MyClass {
constructor() {
this.myProperty = null;
}
}
const o = new MyClass;
return o;
").ToObject();
Console.WriteLine(o?.GetType() ?? "<null>"); //System.Dynamic.ExpandoObject
Console.WriteLine(o?.myProperty ?? "<null>"); //<null>
o.myProperty = "why not this string";
Console.WriteLine(o?.myProperty ?? "<null>"); //why not this string
Console.WriteLine(o?.myProperty?.GetType() ?? "<null>"); //System.String
o.myProperty = 99;
Console.WriteLine(o?.myProperty ?? "<null>"); //99
Console.WriteLine(o?.myProperty?.GetType() ?? "<null>"); //System.Int32
现在 AFAIK 没有内置方法来更改属性并继续在 Javascript 中使用它。我能想到的两个选择:
在 C# 中声明类并通过 SetValue() 将实例传递给 Jint。对对象实例的更改将在 Jint 中可用。
破解类似这样的东西来改变 Jint 中的任意东西:
public static void SetProperty(this Jint.Engine engine, string propertyPath, object value)
{
string tempname = "super_unique_name_that_will_never_collide_with_anything";
engine.SetValue(tempname, value);
engine.Evaluate($@"{propertyPath} = {tempname}; delete globalThis.{tempname};");
}
推荐阅读
- java - 线程如何影响打印功能以及何时调用(Java)
- java - 如何使用 Get 请求特别处理 REST API 中的保留字符,例如值 M&S
- typescript - TypeScript 可以推断对象的属性吗?
- vue.js - 为什么我的 Vue/Nuxt Select 字段状态默认有效?
- android - 这样的布局将如何实现?
- fortran - 在 Fortran 中创建的 HDF5 文件直到模拟结束才写入
- javascript - 悬停时更改 SVG 圆形平铺世界地图上区域的颜色
- javascript - 简化旧的 RegExp
- ios - 创建自定义 Xcode 项目模板
- c++ - c++向量如何
> 管理内存