C# 計算自定義公式的一種解決方案

可實現簡單的四則運算,帶變量名運算,數學公式運算,支持小數運算,不過,數學公式運算要注意字母的大小寫,hanQ從網上找到的資料寫的是 Math.Pow()是錯的,正確可運行的公式應該是Math.pow(),這一點要注意,原理是引用了js,而JS的函數是小寫的,關於JS的函數使用 方式,請參見http://hi.baidu.com/shidadmt/blog/item /fc8dab1a63e59c1e8718bf39.html。

只要是js支持的運算均可以支持。html

效果圖:注意,給出的Demo是form版本的,其餘版本大同小異。c#

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace Eval
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void execBtn_Click(object sender, EventArgs e)
        {
            if (!"".Equals(inTxt.Text))
            {
                MSScriptControl.ScriptControl sc = new MSScriptControl.ScriptControlClass();
                sc.Language = "JavaScript";

                string rval = inTxt.Text;
                rval = rval.Replace("Evaluator_a", val_a.Text);
                string r = "";
                try
                {
                    r = sc.Eval(rval).ToString();
                }
                catch { MessageBox.Show("計算失敗!"); }
                rtLst.Items.Add(inTxt.Text + "=" + ("".Equals(r)?"ERR":r));
                rtLst.SelectedIndex = rtLst.Items.Count - 1;
            }
            else
            {
                MessageBox.Show("請輸入公式!");
            }
        }
    }
}
相關文章
相關標籤/搜索