I'd like to execute a know script method with parameters. Currently I use
because the Execute("MyMethod") hasn't got the option to call it with parameters. Am I wrong or is the use of the Script property the only way to execute a known method?
Nov 11, 2013 at 2:12 AM
You can use
to invoke an existing script function, but doing so is suboptimal for several reasons.
(e.g., storing arguments in a global script object with a well-known name), but that is a brittle approach that would only work for first-party script code.
The other factor to consider is that
are top-level entry points into the script engine's parsing and JIT compilation stack. They're relatively expensive. If all you need to do is invoke a script function that
is already parsed and compiled, these methods are the wrong tool for the job.
property gives you direct access
to an existing script function, which you can then invoke without parsing or compiling additional script code. In addition to making it easy to pass arguments, this is important for performance.
In fact, if the function is one that you call often, we recommend that you cache it and avoid going through
dynamic myMethod = engine.Script.MyMethod;
object result = myMethod(parameter);
By the way, to access a global script function or object by name, you can do this:
dynamic myMethod = engine.Script["MyMethod"];