用动态编译的话最简单啦 string expression = "234*43/2*43^2-234234"; string s = "namespace __ns{public class __c{ public double __v{get{return "+expression+";}} }}"; CompilerResults res = new CSharpCodeProvider().CompileAssemblyFromSource(new CompilerParameters(new string[]{"System.dll"}), s); if (res.Errors.HasErrors) { MessageBox.Show("表达式错误!"); } else { Type c = res.CompiledAssembly.GetType("__ns.__c"); MessageBox.Show(c.GetProperty("__v").GetValue(c.GetConstructor(System.Type.EmptyTypes).Invoke(null), null).ToString()); }
这里面涉及到CodeDom和Reflection 到vs帮助里面看一下就知道了 命名空间 using System.Reflection; using Microsoft.CSharp; using System.CodeDom; using System.CodeDom.Compiler;比较简单,一下就能学会的
乘方直接用 ^ 比如 23^3就是23的3次方 在表达式里面可以用System.Math里面的函数 Sqrt Round Pow 等等 比如string expression = "23*43 + System.Math.Sqrt(43)";如果想省掉System.可以把 string s = "namespace __ns{public class __c{ public double __v{get{return "+expression+";}} }}"; 变成 string s = "using System; namespace __ns{public class __c{ public double __v{get{return "+expression+";}} }}";然后 string expression = "23*43 + Math.Sqrt(43) + Math.Pow(32,0.4)"; // .....
string s = "namespace __ns{public class __c{ public double __v{get{return "+expression+";}} }}";
CompilerResults res = new CSharpCodeProvider().CompileAssemblyFromSource(new CompilerParameters(new string[]{"System.dll"}), s);
if (res.Errors.HasErrors)
{
MessageBox.Show("表达式错误!");
}
else
{
Type c = res.CompiledAssembly.GetType("__ns.__c");
MessageBox.Show(c.GetProperty("__v").GetValue(c.GetConstructor(System.Type.EmptyTypes).Invoke(null), null).ToString());
}
命名空间
using System.Reflection;
using Microsoft.CSharp;
using System.CodeDom;
using System.CodeDom.Compiler;比较简单,一下就能学会的
在表达式里面可以用System.Math里面的函数 Sqrt Round Pow 等等
比如string expression = "23*43 + System.Math.Sqrt(43)";如果想省掉System.可以把
string s = "namespace __ns{public class __c{ public double __v{get{return "+expression+";}} }}";
变成
string s = "using System; namespace __ns{public class __c{ public double __v{get{return "+expression+";}} }}";然后
string expression = "23*43 + Math.Sqrt(43) + Math.Pow(32,0.4)"; // .....
忘了...c#里面^不是乘方的意思(异或?)..跟vb混了 汗死
那就用Math.Pow吧 比如 4的3次方 Math.Pow(4,3)
装饰模式
Class Calculator
{
private object _value;
public object Value
{
get
{
return _value;
}
}
public Calculator Plus(object value)
{
this._value = this._value + value;
}
}其它操作同理。
调用时,只须 实例化一个 Calculator cal = new Calculator()即可。 cal.Plus(5).Plus(6).Mul(3).Sub(7)
当然对于括号的问题要考虑考虑。
如果你的意思是如何实现那样的计算,那么前面已经回答了。都在 System.Math 命名空间里