using System;
using System.CodeDom.Compiler;
using System.Reflection;
using Microsoft.JScript;
namespace TestRunSpeed
{
public class JSEvaluator
{
/// <summary>
/// 返回Integer类型
/// </summary>
/// <param name="statement"></param>
/// <returns></returns>
public static int EvalToInteger(string statement)
{
string s = EvalToString(statement);
return int.Parse(s.ToString());
}
/// <summary>
/// 返回Double类型
/// </summary>
/// <param name="statement"></param>
/// <returns></returns>
public static double EvalToDouble(string statement)
{
string s = EvalToString(statement);
double result;
bool a = double.TryParse(s, out result);
if (a) return result;
else return -99.0;
}
/// <summary>
/// 返回String类型
/// </summary>
/// <param name="statement"></param>
/// <returns></returns>
public static string EvalToString(string statement)
{
object o = EvalToObject(statement);
return o.ToString();
}
/// <summary>
/// 返回Object类型
/// </summary>
/// <param name="statement"></param>
/// <returns></returns>
public static object EvalToObject(string statement)
{
try
{
//根据类型调用指定的方法。绑定约束并匹配指定参数列表
return _evaluatorType.InvokeMember(
"Eval",
BindingFlags.InvokeMethod,
null,
_evaluator,
new object[] { statement }
);
}
catch
{
return "null";
}
}
static JSEvaluator()
{
//创建编译器
CodeDomProvider compiler = CodeDomProvider.CreateProvider("JScript");
//创建引用参数
CompilerParameters parameters = new CompilerParameters();
//在内存中生成输出
parameters.GenerateInMemory = true;
//返回编译结果
CompilerResults results = compiler.CompileAssemblyFromSource(parameters, _jscriptSource);
//获取程序集
Assembly assembly = results.CompiledAssembly;
//获取类型
_evaluatorType = assembly.GetType("Evaluator.Evaluator");
//获取对象实例
_evaluator = Activator.CreateInstance(_evaluatorType);
}
//编译生成对象
private static object _evaluator = null;
//类型
private static Type _evaluatorType = null;
//JScript代码
private static readonly string _jscriptSource =
@"package Evaluator
{
class Evaluator
{
public function Eval(expr : String) : String
{
return eval(expr);
}
}
}";
}
}