Clearscript put Dictionary as function argument

357 Views Asked by At

I have JS code:

function on_save() {
    Service.AddTableRow([{id: 21194, value: "jjkk"}, {id: 1234, value: "Lala"}]);
    return true;
}

Into c# I do:

var engine = new V8ScriptEngine();
engine.AddHostObject("Service", scriptService);
engine.Execute(content);
result = engine.Script.on_save();

Into scriptService I have:

public void AddTableRow(Dictionary<string, object> values)
{
    //but there is invalid argument "values"
    //I also tried List<object> param type but result is the same
}

How can I resolve this issue?

1

There are 1 best solutions below

7
BitCortex On

Try something like this:

public void AddTableRow(IList list) {
    foreach (ScriptObject item in list) {
        Console.WriteLine("{0} -> {1}", item["id"], item["value"]);
    }
}

You can see this sample working here.

EDIT: If you're using something older than ClearScript 6, you can do something like this instead:

public void AddTableRow(dynamic list) {
    int length = list.length;
    for (var i = 0; i < length; ++i) {
        var item = list[i];
        Console.WriteLine("{0} → {1}", item.id, item.value);
    }
}

This technique is also demonstrated here. Newer ClearScript versions support both.