调用:Evaluator.EvalToDouble("(512+100)/300");
using System;
using System.CodeDom.Compiler;
using System.Reflection;
using Microsoft.JScript;
namespace mysoft
{
public class Evaluator
{
public static int EvalToInteger(string statement)
{
string s = EvalToString(statement);
return int.Parse(s.ToString());
}
public static double EvalToDouble(string statement)
{
string s = EvalToString(statement);
return double.Parse(s);
}
public static string EvalToString(string statement)
{
object o = EvalToObject(statement);
return o.ToString();
}
public static object EvalToObject(string statement)
{
return _evaluatorType.InvokeMember(
"Eval",
BindingFlags.InvokeMethod,
null,
_evaluator,
new object[] { statement }
);
}
static Evaluator()
{
ICodeCompiler compiler;
compiler = new JScriptCodeProvider().CreateCompiler();
CompilerParameters parameters;
parameters = new CompilerParameters();
parameters.GenerateInMemory = true;
CompilerResults results;
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;
private static readonly string _jscriptSource =
@"package Evaluator
{
class Evaluator
{
public function Eval(expr : String) : String
{
return eval(expr);
}
}
}";
}
}
相关文章
- JS:JS中常见的 “函数名 is not a function” 错误
- 面试问题 - SQL 中存储过程与函数的区别
- 如何使用 TP中的公共函数 (定义在common/common.php中的函数)
- C++进阶--析构函数中的异常
- C#控制台程序,运行完窗口不退出的方法
- oracle函数nvl,nvl2的区别,nullif函数,coalesce函数
- MySQL中的IFNULL,IF,NULLIF函数
- jQuery的$.get()函数不执行以及php端报错Uncaught Error: Call to a member function bind_param() on boolean in...
- 比较好用的php函数
- MySQL自定义函数与存储过程的创建、使用、删除