首页 > 代码库 > C#数学运算表达式解释器

C#数学运算表达式解释器

C#数学运算表达式解释器


测试文件内容:

a=2+3*2;
b=2*(2+3);
浏览按钮事件处理程序:

        private void button_browse_Click(object sender, EventArgs e)
        {
            OpenFileDialog fbd = new OpenFileDialog();
            fbd.Title = "请选择一个文件:";
            fbd.CheckFileExists = true;
            fbd.CheckPathExists = true;
            fbd.Filter = "*.txt(文本文件)|*.txt|*.*(所有文件)|*.*";
            fbd.FileName = Environment.GetFolderPath(Environment.SpecialFolder.MyComputer);
            if (fbd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                textBox_saveDir.Text = fbd.FileName;
                try
                {
                    FileStream fs = new FileStream(fbd.FileName, FileMode.Open, FileAccess.Read);
                    StreamReader sr = new StreamReader(fs);
                    while (!sr.EndOfStream)
                    {
                        string line = sr.ReadLine();
                        analyse(line);
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show("错误:" + ex.Message + "\r\n堆栈:" + ex.StackTrace);
                }
            }
        }
分析一行表达式:

        private void analyse(string line)
        {
            //以分号作为结束符,支持一行内写多个语句
            string[] expA = line.Split(new string[] { ";" }, StringSplitOptions.RemoveEmptyEntries);
            for (int i = 0; i < expA.Length; i++)
            {
                analyseExpA(expA[i]);
            }
        }
计算一条表达式:
        private void analyseExpA(string expA)
        {
            string[] expB = expA.Split(new string[] { "=" }, StringSplitOptions.RemoveEmptyEntries);
            for (int i = 0; i < expB.Length; i++ )
            {
                Regex reg = new Regex("[a-zA-Z]");
                if (!reg.IsMatch(expB[i]))
                {
                    object obj = EvalExpress(expB[i]);
                    if (obj != null)
                    {
                        textBox1.Text += expA + " = " + obj.ToString() + "\r\n";
                    }
                    else
                    {
                        textBox1.Text += expA + ",无法识别的表达式\r\n";
                    }
                }
            }
        }

源码下载:C#数学运算表达式解释器源码