两个数的简单运算,如“4+5”“8*9”,可参阅。using System; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using System.Data; namespace WindowsApplication5 { /// <summary> /// Form1 的摘要说明。 /// </summary> public class Form1 : System.Windows.Forms.Form { private System.Windows.Forms.TextBox textBox1; private System.Windows.Forms.Button button1; /// <summary> /// 必需的设计器变量。 /// </summary> private System.ComponentModel.Container components = null;
//定义运算,返回结果。 public int calculate (char op,int x,int y) { int z=0; if (op=='+') z=x+y; if (op=='-') z=x-y; if (op=='*') z=x*y; if (op=='/') z=x/y; return z; } //入栈操作 Stack myStack=new Stack();
/*public void stackpush (char s) { switch (s) { case '0':myStack.Push(0); break; case '1':myStack.Push(1); break; case '2':myStack.Push(2); break; case '3':myStack.Push(3); break; case '4':myStack.Push(4); break; case '5':myStack.Push(5); break; case '6':myStack.Push(6); break; case '7':myStack.Push(7); break; case '8':myStack.Push(8); break; case '9':myStack.Push(9); break; default :myStack.Push(s); break; } }*/ public int stackpopnum (char s) { s=(char)myStack.Pop(); int num=0; switch (s) { case '0':num=0; break; case '1':num=1; break; case '2':num=2; break; case '3':num=3; break; case '4':num=4; break; case '5':num=5; break; case '6':num=6; break; case '7':num=7; break; case '8':num=8; break; case '9':num=9; break;
}return num; } //出栈 public int stackpop () { int i; i=(int)myStack.Pop(); int j=1; while (((char)myStack.Peek()>='0')&&((char)myStack.Peek()<='9')) { i=(int)myStack.Pop()*(int)Math.Pow(10,j)+i; j++; } return i; } public Form1() { // // Windows 窗体设计器支持所必需的 // InitializeComponent(); // // TODO: 在 InitializeComponent 调用后添加任何构造函数代码 // } /// <summary> /// 清理所有正在使用的资源。 /// </summary> protected override void Dispose( bool disposing ) { if( disposing ) { if (components != null) { components.Dispose(); } } base.Dispose( disposing ); } #region Windows 窗体设计器生成的代码 /// <summary> /// 设计器支持所需的方法 - 不要使用代码编辑器修改 /// 此方法的内容。 /// </summary> private void InitializeComponent() { this.textBox1 = new System.Windows.Forms.TextBox(); this.button1 = new System.Windows.Forms.Button(); this.SuspendLayout(); // // textBox1 // this.textBox1.Location = new System.Drawing.Point(64, 32); this.textBox1.Name = "textBox1"; this.textBox1.Size = new System.Drawing.Size(176, 21); this.textBox1.TabIndex = 0; this.textBox1.Text = "textBox1"; // // button1 // this.button1.Location = new System.Drawing.Point(80, 120); this.button1.Name = "button1"; this.button1.Size = new System.Drawing.Size(72, 24); this.button1.TabIndex = 1; this.button1.Text = "cal"; this.button1.Click += new System.EventHandler(this.button1_Click); // // Form1 // this.AutoScaleBaseSize = new System.Drawing.Size(6, 14); this.ClientSize = new System.Drawing.Size(292, 273); this.Controls.Add(this.button1); this.Controls.Add(this.textBox1); this.Name = "Form1"; this.Text = "Form1"; this.ResumeLayout(false); } #endregion /// <summary> /// 应用程序的主入口点。 /// </summary> [STAThread] static void Main() { Application.Run(new Form1()); } private void button1_Click(object sender, System.EventArgs e) { string s=textBox1.Text; int i=s.Length; int j=0; while ((j<i)) { myStack.Push(s[j]); j++; }
int x=stackpopnum ((char)myStack.Peek()); char op=(char)myStack.Pop(); int y=stackpopnum ((char)myStack.Peek()); int z=calculate (op,x,y); //
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
namespace WindowsApplication5
{
/// <summary>
/// Form1 的摘要说明。
/// </summary>
public class Form1 : System.Windows.Forms.Form
{
private System.Windows.Forms.TextBox textBox1;
private System.Windows.Forms.Button button1;
/// <summary>
/// 必需的设计器变量。
/// </summary>
private System.ComponentModel.Container components = null;
//定义运算,返回结果。
public int calculate (char op,int x,int y)
{
int z=0;
if (op=='+') z=x+y;
if (op=='-') z=x-y;
if (op=='*') z=x*y;
if (op=='/') z=x/y;
return z;
}
//入栈操作
Stack myStack=new Stack();
/*public void stackpush (char s)
{
switch (s)
{
case '0':myStack.Push(0);
break;
case '1':myStack.Push(1);
break;
case '2':myStack.Push(2);
break;
case '3':myStack.Push(3);
break;
case '4':myStack.Push(4);
break;
case '5':myStack.Push(5);
break;
case '6':myStack.Push(6);
break;
case '7':myStack.Push(7);
break;
case '8':myStack.Push(8);
break;
case '9':myStack.Push(9);
break;
default :myStack.Push(s);
break;
}
}*/ public int stackpopnum (char s)
{
s=(char)myStack.Pop();
int num=0;
switch (s)
{
case '0':num=0;
break;
case '1':num=1;
break;
case '2':num=2;
break;
case '3':num=3;
break;
case '4':num=4;
break;
case '5':num=5;
break;
case '6':num=6;
break;
case '7':num=7;
break;
case '8':num=8;
break;
case '9':num=9;
break;
}return num;
}
//出栈
public int stackpop ()
{
int i;
i=(int)myStack.Pop();
int j=1;
while (((char)myStack.Peek()>='0')&&((char)myStack.Peek()<='9'))
{
i=(int)myStack.Pop()*(int)Math.Pow(10,j)+i;
j++;
}
return i;
} public Form1()
{
//
// Windows 窗体设计器支持所必需的
//
InitializeComponent(); //
// TODO: 在 InitializeComponent 调用后添加任何构造函数代码
//
} /// <summary>
/// 清理所有正在使用的资源。
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
} #region Windows 窗体设计器生成的代码
/// <summary>
/// 设计器支持所需的方法 - 不要使用代码编辑器修改
/// 此方法的内容。
/// </summary>
private void InitializeComponent()
{
this.textBox1 = new System.Windows.Forms.TextBox();
this.button1 = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// textBox1
//
this.textBox1.Location = new System.Drawing.Point(64, 32);
this.textBox1.Name = "textBox1";
this.textBox1.Size = new System.Drawing.Size(176, 21);
this.textBox1.TabIndex = 0;
this.textBox1.Text = "textBox1";
//
// button1
//
this.button1.Location = new System.Drawing.Point(80, 120);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(72, 24);
this.button1.TabIndex = 1;
this.button1.Text = "cal";
this.button1.Click += new System.EventHandler(this.button1_Click);
//
// Form1
//
this.AutoScaleBaseSize = new System.Drawing.Size(6, 14);
this.ClientSize = new System.Drawing.Size(292, 273);
this.Controls.Add(this.button1);
this.Controls.Add(this.textBox1);
this.Name = "Form1";
this.Text = "Form1";
this.ResumeLayout(false); }
#endregion /// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main()
{
Application.Run(new Form1());
} private void button1_Click(object sender, System.EventArgs e)
{
string s=textBox1.Text;
int i=s.Length;
int j=0;
while ((j<i))
{
myStack.Push(s[j]);
j++;
}
int x=stackpopnum ((char)myStack.Peek());
char op=(char)myStack.Pop();
int y=stackpopnum ((char)myStack.Peek());
int z=calculate (op,x,y);
//
textBox1.Text=z.ToString();
myStack.Clear(); }
}
}
使用方法:Console.WriteLine("Test0: {0}", Evaluator.EvaluateToInteger("(30 + 4) * 2"));using System;
using System.CodeDom;
using System.CodeDom.Compiler;
using Microsoft.CSharp;
using System.Text;
using System.Reflection;namespace ADOGuy
{
/// <summary>
/// Summary description for Class1.
/// </summary>
public class Evaluator
{
#region Construction
public Evaluator(EvaluatorItem[] items)
{
ConstructEvaluator(items);
} public Evaluator(Type returnType, string expression, string name)
{
EvaluatorItem[] items = { new EvaluatorItem(returnType, expression, name) };
ConstructEvaluator(items);
} public Evaluator(EvaluatorItem item)
{
EvaluatorItem[] items = { item };
ConstructEvaluator(items);
} private void ConstructEvaluator(EvaluatorItem[] items)
{
ICodeCompiler comp = (new CSharpCodeProvider().CreateCompiler());
CompilerParameters cp = new CompilerParameters();
cp.ReferencedAssemblies.Add("system.dll");
cp.ReferencedAssemblies.Add("system.data.dll");
cp.ReferencedAssemblies.Add("system.xml.dll");
cp.GenerateExecutable = false;
cp.GenerateInMemory = true; StringBuilder code = new StringBuilder();
code.Append("using System; \n");
code.Append("using System.Data; \n");
code.Append("using System.Data.SqlClient; \n");
code.Append("using System.Data.OleDb; \n");
code.Append("using System.Xml; \n");
code.Append("namespace ADOGuy { \n");
code.Append(" public class _Evaluator { \n");
foreach(EvaluatorItem item in items)
{
code.AppendFormat(" public {0} {1}() ",
item.ReturnType.Name,
item.Name);
code.Append("{ ");
code.AppendFormat(" return ({0}); ", item.Expression);
code.Append("}\n");
}
code.Append("} }"); CompilerResults cr = comp.CompileAssemblyFromSource(cp, code.ToString());
if (cr.Errors.HasErrors)
{
StringBuilder error = new StringBuilder();
error.Append("Error Compiling Expression: ");
foreach (CompilerError err in cr.Errors)
{
error.AppendFormat("{0}\n", err.ErrorText);
}
throw new Exception("Error Compiling Expression: " + error.ToString());
}
Assembly a = cr.CompiledAssembly;
_Compiled = a.CreateInstance("ADOGuy._Evaluator");
}
#endregion #region Public Members
public int EvaluateInt(string name)
{
return (int) Evaluate(name);
} public string EvaluateString(string name)
{
return (string) Evaluate(name);
} public bool EvaluateBool(string name)
{
return (bool) Evaluate(name);
} public object Evaluate(string name)
{
MethodInfo mi = _Compiled.GetType().GetMethod(name);
return mi.Invoke(_Compiled, null);
}
#endregion #region Static Members
static public int EvaluateToInteger(string code)
{
Evaluator eval = new Evaluator(typeof(int), code, staticMethodName);
return (int) eval.Evaluate(staticMethodName);
} static public string EvaluateToString(string code)
{
Evaluator eval = new Evaluator(typeof(string), code, staticMethodName);
return (string) eval.Evaluate(staticMethodName);
}
static public bool EvaluateToBool(string code)
{
Evaluator eval = new Evaluator(typeof(bool), code, staticMethodName);
return (bool) eval.Evaluate(staticMethodName);
} static public object EvaluateToObject(string code)
{
Evaluator eval = new Evaluator(typeof(object), code, staticMethodName);
return eval.Evaluate(staticMethodName);
}
#endregion #region Private
const string staticMethodName = "__foo";
Type _CompiledType = null;
object _Compiled = null;
#endregion
} public class EvaluatorItem
{
public EvaluatorItem(Type returnType, string expression, string name)
{
ReturnType = returnType;
Expression = expression;
Name = name;
} public Type ReturnType;
public string Name;
public string Expression;
}
}