首页 > 解决方案 > 将对象传递给jint中的函数并返回一个值

问题描述

我试图通过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");

标签: c#.netjson.netjint

解决方案


文档中所示,您应该将 POCOcar直接传递给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是一个具有字符串属性的 POCO Type,例如

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

演示小提琴在这里


推荐阅读