我正在考虑将我们的应用程序从使用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,而我更不愿意这样做。
发布于 2018-03-07 13:58:49
您可以通过JavaScript直接使用dynamic数组。
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);
}
}https://stackoverflow.com/questions/49149138
复制相似问题