"(2+3)-5*6^2" 是一个字符串,他也有可能是其他的算术表达式
求一算法 能获得他的值本人一直在尝试用 栈实现 理论上栈可以实现.希望高手门把你们的实现代码给我看看学习一下,本贴为学习贴 :)
求一算法 能获得他的值本人一直在尝试用 栈实现 理论上栈可以实现.希望高手门把你们的实现代码给我看看学习一下,本贴为学习贴 :)
解决方案 »
- C#文件遍历的疑难杂症,老医生进来给把把脉?
- WCF,使用HTTP方式返回值时,报错"已超过传入消息(65536)的最大消息大小配额。"
- 正则表达式匹配RTF中的图片
- 100分在问两个问题
- (急)類對象輿類的轉換問題
- MSDN
- 共享程序集路径问题!!!
- 请教一个函数调用的问题?
- 如何用SendMessage API让修改的系统环境变量立即生效,在线等!!!
- 怎样把DataGrid中数据导出成EXCEL。一定要C#的语言来写哈!!!
- JAVASCRIPT代码转换过来的问题
- 新手问题: DataGrid中使用了模版列,放入RadioButtonList,怎样获得该RadioButtonList选中哪一项?
using System.CodeDom.Compiler;
using Microsoft.CSharp;
using System.Reflection;
using System.Text;namespace ConsoleApplication22
{
/// <summary>
/// Class1 的摘要说明。
/// </summary>
class Class1
{
/// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main(string[] args)
{
//
// TODO: 在此处添加代码以启动应用程序
//
int i = (int)Calc("1+2*3");
Console.WriteLine(i.ToString());
Console.ReadLine(); } public static object Calc(string expression)
{
string className = "Calc";
string methodName = "Run";
expression=expression.Replace("/","*1.0/");
// 创建编译器实例。
ICodeCompiler complier = (new CSharpCodeProvider().CreateCompiler());
// 设置编译参数。
CompilerParameters paras = new CompilerParameters();
paras.GenerateExecutable = false;
paras.GenerateInMemory = true;
// 创建动态代码。
StringBuilder classSource = new StringBuilder();
classSource.Append("public class "+ className +"\n");
classSource.Append("{\n");
classSource.Append(" public object " + methodName + "()\n");
classSource.Append(" {\n");
classSource.Append(" return "+ expression + ";\n");
classSource.Append(" }\n");
classSource.Append("}");
//System.Diagnostics.Debug.WriteLine(classSource.ToString());
// 编译代码。
CompilerResults result = complier.CompileAssemblyFromSource(paras, classSource.ToString());
// 获取编译后的程序集。
Assembly assembly = result.CompiledAssembly;
// 动态调用方法。
object eval = assembly.CreateInstance(className);
MethodInfo method = eval.GetType().GetMethod(methodName);
object reobj = method.Invoke(eval, null);
GC.Collect();
return reobj; } }
}
参考: http://www.codeproject.com/useritems/evaluator.asp当然也可一直接使用jscript.net 语言编译一个dll来计算.比如:
1) Create a file named CustomEval.js (File | New | File | Script) as
follows:// JScript source code
class CustomEval
{
static function eval(strExp)
{
return eval(strExp);
}}2) Compile this source code from the command line:jsc /t:library CustomEval.jswhich should produce CustomEval.dll3) Reference this assembly from your VB .Net or C# project as well as
the Microsoft.JScript assembly.4) Use the eval method of CustomEval as follows (since the method is
static, you don't need to instantiate CustomEval. result = CustomEval.eval("2+3")