【问题标题】:Pass an object to a function in jint and return a value将对象传递给jint中的函数并返回一个值
【发布时间】:2021-01-27 09:06:09
【问题描述】:

我正在尝试通过jint 将对象传递给javascript 函数并返回一个值。但这似乎不起作用。这是我迄今为止尝试过的 -

错误 -

Jint.Runtime.JavaScriptException: 'obj is undefined'

使用以下代码-

var carObj = JsonSerializer.Serialize(car);  

var engine = new Jint.Engine();
engine.SetValue("obj", carObj);

var value = engine
           .Execute("const result = (function car(obj) { const type = obj.Type; return type;})()")
           .GetValue("result");

【问题讨论】:

  • 我不熟悉 jint,但我猜测 function car(obj) 创建了一个本地 obj 来隐藏您的“全局”obj。而那个本地的obj 确实是未定义的。我会尝试的第一件事就是做function car() { ... // same code from here
  • @Fildor 我尝试了一个没有任何参数的简单函数,它似乎可以工作 - function car() { const myTemplate = 3 + 5; 只有我需要知道传递一个对象
  • 你试过我的建议了吗?我相信obj 应该在脚本中全局可用。
  • 我试过了,没有错误,结果是undefined
  • 好的,那么我的假设似乎不正确,对不起。

标签: c# .net json.net jint


【解决方案1】:

docs 所示,您应该将 POCO car 直接传递给 Jint.Engine,而不是尝试将其序列化为 JSON。 Jint 将使用反射来访问其成员。

因此您的代码可以重写如下:

var value = new Jint.Engine()  // Create the Jint engine
    .Execute("function car(obj) { const type = obj.Type; return type;}") // Define a function car() that accesses the Type field of the incoming obj and returns it.
    .Invoke("car", car);  // Invoke the car() function on the car POCO, and return its result.

或等价于:

var value = new Jint.Engine()
    .SetValue("obj", car) // Define a "global" variable "obj"
    .Execute("const result = (function car(obj) { const type = obj.Type; return type;})(obj)") // Define the car() function, call it with "obj", and set the value in "result"
    .GetValue("result"); // Get the evaluated value of "result"

或者

var value = new Jint.Engine()  // Create the Jint engine
    .SetValue("obj", car) // Define a "global" variable "obj"
    .Execute("function car(obj) { const type = obj.Type; return type;}; car(obj);") // Define the car() function, and call it with "obj".
    .GetCompletionValue();  // Get the last evaluated statement completion value            

这里我假设car 是一个具有字符串属性Type 的POCO,例如

var car = new 
{
    Type = "studebaker convertible",
};

演示小提琴here.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-06-27
    • 1970-01-01
    • 2016-11-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-23
    相关资源
    最近更新 更多