如文档中所示,您应该将 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",
};
演示小提琴在这里。