gpt4 book ai didi

c# - 将对象传递给 jint 中的函数并返回值

转载 作者:行者123 更新时间:2023-12-05 04:53:56 27 4
gpt4 key购买 nike

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

最佳答案

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",
};

演示 fiddle here .

关于c# - 将对象传递给 jint 中的函数并返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65915909/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com