using System; using System.CodeDom.Compiler; using System.Reflection; using System.Web.UI; using Microsoft.JScript; namespace HuaTong.General.Utility { /// <summary> /// JScriptProvider包装 /// </summary> public static class JScript { private static object js = null; private static Type jsType = null; private static readonly string jsSource = @"package JScript { class JScript { public function Eval(expr : String) : Object { return eval(expr); } } }"; /// <summary> /// 构造javascript运行时对象 /// </summary> static JScript() { JScriptCodeProvider compiler = new JScriptCodeProvider(); CompilerParameters parameters = new CompilerParameters(); parameters.GenerateInMemory = true; CompilerResults results = compiler.CompileAssemblyFromSource(parameters, jsSource); Assembly assembly = results.CompiledAssembly; jsType = assembly.GetType("JScript.JScript"); js = Activator.CreateInstance(jsType); } /// <summary> /// 获取表达式的值 /// </summary> /// <returns></returns> public static int EvalToInt32(string code) { string s = EvalToString(code); return int.Parse(s); } /// <summary> /// 获取表达式的值 /// </summary> /// <returns></returns> public static double EvalToDouble(string code) { string s = EvalToString(code); return double.Parse(s); } /// <summary> /// 获取表达式的值 /// </summary> /// <returns></returns> public static string EvalToString(string code) { object o = EvalToObject(code); return o.ToString(); } /// <summary> /// 获取表达式的值 /// </summary> /// <returns></returns> public static object EvalToObject(string code) { return jsType.InvokeMember("Eval", BindingFlags.InvokeMethod, null, js, new object[] { code }); } } }