0

如何从传递给主机 C# 方法的 JS 对象转换为名称和值对的字典?我的问题是如何解释在 exec 函数中收到的“对象”。如果它们是 int 的,我可以使用...

foreach (int i in args)...

...但他们是...什么?

例如,在一个 JS 文件中,我有

  myApi.exec("doThang", { dog: "Rover", cat: "Purdy", mouse: "Mini", <non-specific list of more...> } );

在 C# 中我有

public void foo()
{
  var engine = new V8ScriptEngine();
  engine.AddHostObject("myApi", a);  // see below

  // load the above JS
  string script = loadScript();

  // execute that script
  engine.Execute(script);

}

public class a 
{
  public void exec(string name, params object[] args){

  // - how to iterate the args and create say a dictionary of key value pairs? 

  }
}

编辑:现在我了解'params'关键字不是ClearScript的特定部分,因此更改了问题的细节。

4

1 回答 1

2

您可以使用ScriptObject. 脚本对象可以具有索引属性以及命名属性,因此您可以创建两个字典:

public void exec(string name, ScriptObject args) {
    var namedProps = new Dictionary<string, object>();
    foreach (var name in args.PropertyNames) {
        namedProps.Add(name, args[name]);
    }
    var indexedProps = new Dictionary<int, object>();
    foreach (var index in args.PropertyIndices) {
        indexedProps.Add(index, args[index]);
    }
    Console.WriteLine(namedProps.Count);
    Console.WriteLine(indexedProps.Count);
}

如果您不期望或不关心索引属性,您可以跳过indexedProps. 或者您可以构建一个Dictionary<object, object>实例来保存两者。

于 2020-04-18T15:40:33.790 回答