gpt4 book ai didi

javascript - 如何使用 Clearscript 将 CLR 类型的 native JS 数组转换为 CLR 数组

转载 作者:行者123 更新时间:2023-12-03 02:21:11 26 4
gpt4 key购买 nike

我正在考虑将我们的应用程序从使用 JavaScript.NET 转换为(Noesis)使用 ClearScript。

我们的应用包含大量用户创建的用于财务计算的 Javascript 算法/表达式 - 如果可能的话,我宁愿避免更改这些算法/表达式

目前,JavaScript.NET 中的许多用户定义算法都遵循创建包含主机类型的 JavaScript 数组并将其作为参数传递给另一个主机类型上的函数的模式。对于 JavaScript.NET,这种转换“正常”。请参阅下面的代码了解我正在尝试执行的操作:

using System;
using Microsoft.ClearScript;
using Microsoft.ClearScript.V8;

namespace ClearscriptPlayground
{
class Program
{
static void Main(string[] args)
{
using (var engine = new V8ScriptEngine())

{
var myClass = new MyClass();;
engine.AddHostObject("instance", myClass);
engine.AddHostType("MyType", HostItemFlags.DirectAccess, typeof(MyType));
engine.Execute(
@"var params = [new MyType('bye', 10),
new MyType('hello', 10)];

instance.SomethingElse(params)");

Console.ReadLine();
}
}
}

public class MyClass
{
// public void SomethingElse(ITypedArray<MyType> foo)
// {
// // Doesn't work.
// }

// public void SomethingElse(MyType[] foo)
// {
// // Doesn't work.
// }

// public void SomethingElse(dynamic foo)
// {
// var mapped = foo as ITypedArray<MyType>; // Doesn't work
// var mapped = foo as MyType[]; // Doesn't work either
// }

public void SomethingElse(ScriptObject foo)
{
// Works, but how best to convert to MyType[] or similar?
}
}

public struct MyType
{
public string Foo;
public int Bar;

public MyType(string foo, int bar)
{
Foo = foo;
Bar = bar;
}
}
}

NB:我知道我可以使用 params = host.newArr(MyType, 2); 创建一个主机数组,这会起作用 - 但这意味着修改所有用户维护的 JavaScript,我真的宁愿避免。

最佳答案

您可以直接通过dynamic使用JavaScript数组:

public void SomethingElse(dynamic foo)
{
var length = foo.length;
for (var i = 0; i < length; ++i)
{
var my = (MyType)foo[i];
Console.WriteLine("{0} {1}", my.Foo, my.Bar);
}
}

关于javascript - 如何使用 Clearscript 将 CLR 类型的 native JS 数组转换为 CLR 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49149138/

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