2

Here is the C# code:

string jsScript = "var x = {A: 10, B: 100}";
scriptEngine.Evaluate(jsScript);
var result = scriptEngine.Evaluate("x");

The result is an instance of WindowsScriptItem object, how can I get the values 10 and 100?

Zach
  • 5,715
  • 12
  • 47
  • 62

1 Answers1

3

If you know the object's property names, you can do this:

dynamic dynamicResult = result;
Console.WriteLine(dynamicResult.A);
Console.WriteLine(dynamicResult.B);

If you don't know the property names, you can do this:

dynamic dynamicResult = result;
foreach (var name in dynamicResult.GetDynamicMemberNames())
    Console.WriteLine("{0}: {1}", name, dynamicResult[name]);

Obviously you'll need something more sophisticated if the object's property values can themselves be objects.

BitCortex
  • 3,328
  • 1
  • 15
  • 19
  • Is it possible to perform such a foreach when you use Engine.Execute method? This method is void (and also the Evaluate method), so how to assign a result? Thanks. – NoChance Dec 15 '20 at 20:28
  • 1
    `Execute` is `void`, but `Evaluate` returns a result. If that result is a script object, the above should work. You can also use the `ScriptObject` class to enumerate properties without `dynamic`, which should be more efficient. – BitCortex Dec 16 '20 at 17:15
  • Thanks for your help. – NoChance Dec 16 '20 at 19:32