首页 > 解决方案 > 金特。如何设置类的属性或调用方法?

问题描述

使用 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

解决方案


要访问从 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 中使用它。我能想到的两个选择:

  1. 在 C# 中声明类并通过 SetValue() 将实例传递给 Jint。对对象实例的更改将在 Jint 中可用。

  2. 破解类似这样的东西来改变 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};");
}

推荐阅读