C # dynamic execution JS

Sometimes need, a program embedded in a flexible self-defined logic calculation, using C # loading JS script forms may be implemented;

// 添加引用 using Microsoft.JScript;
string jsStr = "var i=100; i++; i=i*100; var obj = {a:i};";

Stopwatch sw = new Stopwatch();
sw.Start();
object ret1 = null;
try
{
    ret1 = Eval.JScriptEvaluate(jsStr, VsaEngine.CreateEngine());
}
catch (Exception ex)
{
    MessageBox.Show(ex.StackTrace.ToString(), "执行失败", MessageBoxButtons.OK, MessageBoxIcon.Error);
    return;
}

sw.Stop();

string res = "";
if (ret1 is ArrayObject)
{
    // 数组
    ArrayObject arr = (ArrayObject)ret1;
                
    res = arr[0].ToString();
}
else if (ret1 is JSObject)
{
    // objects 
    the JSObject obj = (the JSObject) RET1;

    res = obj["a"].ToString();
}
else
{
    // single value 
    RES = ret1.ToString ();
}

MessageBox.Show(res + " 用时:" + sw.ElapsedMilliseconds.ToString() + "ms");

 

Guess you like

Origin www.cnblogs.com/zjfree/p/11927382.html