c# - 将对象传递给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");
解决方案
如文档中所示,您应该将 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",
};
演示小提琴在这里。
推荐阅读
- fiware - 添加嵌套的 OPC-UA 变量导致“字符串不能被强制转换为 nodeId”
- azure-active-directory - 通过 Azure Devops 的 CI/CD 在数据块工作区部署中的令牌问题
- python - 在linux中读取和打印多对象json文件
- xml - 如何比较 Xsl 中的两个日期?
- sql - 解释计划后非常慢的oracle sql快速
- node.js - 从sql server获取两个日期之间的数据
- highcharts - Highcharts Dynamic 使用字典/列表 django 数据集
- javascript - React 状态下出现错误“无法读取未定义的属性‘fname’”
- python - 将决策树作为 PNG 文件获取时出错
- flutter - 如何在不打开电子邮件应用程序的情况下发送电子邮件?