using System;
using System.CodeDom;
using System.CodeDom.Compiler;
using Microsoft.CSharp;
using System.Reflection;
public class Eval
{
static object GetValue(string value)
{
string codeSnippet = "using System; " + "/r/n" +
"namespace CzG {" + "/r/n" +
" public class Eval" + "/r/n" +
" {" + "/r/n" +
" public Eval(){} " + "/r/n" +
" public object GetValue()" + "/r/n" +
" {" + "/r/n" +
" return " + value + ";" + "/r/n" +
" }" + "/r/n" +
" } }";
CodeSnippetCompileUnit unit = new CodeSnippetCompileUnit(codeSnippet);
ICodeCompiler compiler = new CSharpCodeProvider().CreateCompiler();
CompilerParameters para = new CompilerParameters();
para.ReferencedAssemblies.Add("System.dll");
para.GenerateInMemory = true;
para.GenerateExecutable = false;
para.OutputAssembly = "Eval.dll";
Assembly asm = compiler.CompileAssemblyFromDom(para, unit).CompiledAssembly;
Type type = asm.GetType("CzG.Eval");
MethodInfo mi = type.GetMethod("GetValue", BindingFlags.Public | BindingFlags.Instance);
object obj = asm.CreateInstance("CzG.Eval");
return mi.Invoke(obj, null);
}
static void Main()
{
Console.WriteLine(Eval.GetValue("125 -23"));
Console.WriteLine(Eval.GetValue("125<23"));
}
}
using Microsoft.JScript;
using Microsoft.JScript.Vsa;
using Microsoft.Vsa;
class MyEval
{
/// <summary>
/// 四则混合运算
/// </summary>
/// <param name="s">计算表达式</param>
/// <returns>计算结果</returns>
/// <example>
/// <code>
/// object x = Mathx.Eval("1+2*2-6/2");
/// </code>
/// </example>
public static object Eval(string s)
{
VsaEngine v = new VsaEngine();
v.InitVsaEngine("", new BaseVsaSite());
return Microsoft.JScript.Eval.JScriptEvaluate(s, v);
}
static void Main()
{
System.Console.WriteLine(Eval("65-23"));
}
}