c#中动态输入和计算 代数表达式
作者:互联网
原文链接:https://blog.csdn.net/liyun211/article/details/48519857
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
using System.ComponentModel;
using System.CodeDom;
using System.CodeDom.Compiler;
using Microsoft.JScript;
using System.Reflection;
下面是一个完整的类,代码已经测试过
/// <summary>
/// 动态求值
/// </summary>
public class Evaluator
{
/// <summary>
/// 计算结果,如果表达式出错则抛出异常
/// </summary>
/// <param name="statement">表达式,如"1+2+3+4"</param>
/// <returns>结果</returns>
public static object Eval(string statement)
{
return _evaluatorType.InvokeMember(
"Eval",
BindingFlags.InvokeMethod,
null,
_evaluator,
new object[] { statement }
);
}
/// <summary>
///
/// </summary>
static Evaluator()
{
//构造JScript的编译驱动代码
CodeDomProvider provider = CodeDomProvider.CreateProvider("JScript");
CompilerParameters parameters;
parameters = new CompilerParameters();
parameters.GenerateInMemory = true;
CompilerResults results;
results = provider.CompileAssemblyFromSource(parameters, _jscriptSource);
Assembly assembly = results.CompiledAssembly;
_evaluatorType = assembly.GetType("Evaluator");
_evaluator = Activator.CreateInstance(_evaluatorType);
}
private static object _evaluator = null;
private static Type _evaluatorType = null;
/// <summary>
/// JScript代码
/// </summary>
private static readonly string _jscriptSource =
@"class Evaluator
{
public function Eval(expr : String) : String
{
return eval(expr);
}
}";
}
调用很简单:Evaluator.Eval( "4*9+8" ) 返回的object 对象转化为数字就是计算的结果
标签:parameters,c#,System,JScript,static,using,Evaluator,代数,表达式 来源: https://www.cnblogs.com/zhanglinfengnepdi/p/11758297.html