2012-05-02 44 views
0

我制作了一个GUI计算器。所以当有人按下按钮时,数字和符号会显示在标签上,然后当他们按下输入键时,计算机会捕捉到字符串,这就是我需要帮助的地方。我知道在Python中有一个可以使用的eval语句,在C#中有类似的东西。如何评估以字符串形式给出的算术表达式

这是代码,如果有帮助。 具体看方法button_click

public class form1 : Form 
{ 
    private Label lab; 
    private Button button2; 
    private Button button; 
    private Button plus; 
    private MathFunctions.MathParser calc; 

    public static void Main() 
    { 
     Application.Run(new form1()); 
    } 

    public form1() 
    { 
     // Initialize controls 
     ... 
    } 

    private void button_Click(object sender,System.EventArgs e) 
    { 
     string answer = lab.Text; 
    } 

    private void button2_Click(object sender,System.EventArgs e) 
    { 
     lab.Text = lab.Text + "2"; 
    } 

    private void button_plus(object sender,System.EventArgs e) 
    { 
     lab.Text = lab.Text + "+"; 
    } 
} 
+0

究竟发生了什么,你想发生什么?尽可能具体 –

+1

可能的重复? http://stackoverflow.com/questions/355062/is-there-a-string-math-evaluator-in-net – Josh

+1

请尝试浓缩您的代码示例以便将来的问题分成几行。这里有太多无关的代码。 –

回答

1

在C#中你没有eval。原则上,您可以在运行时生成代码,编译代码,进行汇编,然后执行代码,或者通过发布IL来释放动态方法,但所有这些都不是非常简单。

我建议你只用一种众所周知的方法解析字符串,然后创建expression tree

或者您可以使用不推荐使用的JavaScript引擎仅用于解析表达式。

Best and shortest way to evaluate mathematical expressions

0

既然你熟悉Python,为什么不使用它呢?在你的C#代码中创建IronPyton脚本引擎对象。这里有一个片段:

string expression = lab.Text; // @"540 + 4/3" try to test 

ScriptEngine engine = Python.CreateEngine(); 
ScriptSource source = engine.CreateScriptSourceFromString(expression, SourceCodeKind.Expression); 

int result = source.Execute<int>(); 
相关问题