From here I wrote a more compact and efficient version of JScript C. Scott Allen's built-in Eval caller ( https://odetocode.com/articles/80.aspx ):
using System; using System.CodeDom.Compiler; using Microsoft.JScript; class JS { private delegate object EvalDelegate(String expr); private static EvalDelegate moEvalDelegate = null; public static object Eval(string expr) { return moEvalDelegate(expr); } public static T Eval<T>(string expr) { return (T)Eval(expr); } public static void Prepare() { } static JS() { const string csJScriptSource = @"package _{ class _{ static function __(e) : Object { return eval(e); }}}"; var loParameters = new CompilerParameters() { GenerateInMemory = true }; var loMethod = (new JScriptCodeProvider()).CompileAssemblyFromSource(loParameters, csJScriptSource).CompiledAssembly.GetType("_._").GetMethod("__"); moEvalDelegate = (EvalDelegate)Delegate.CreateDelegate(typeof(EvalDelegate), loMethod); } }
Just use it like this:
JS.Eval<Double>("1 + 4 + 5 / 99");
Returns:
5.05050505050505
You can expand it to pass the values โโof variables, if you want, for example, pass it to the dictionary of names & values. The first use of the static class will take 100-200 ms, after which it is largely instantaneous and does not require a separate DLL. Call JS.Prepare () to precompile to stop the initial delay if you want.
Aaron murgatroyd
source share