2012-05-02 46 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>(); 
相關問題