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("请输入公式!");
            }
        }
    }
}
相关文章
相关标签/搜索