表达式计算的代码

来源:互联网 发布:照片恢复软件下载 编辑:程序博客网 时间:2024/05/21 12:41
 

 

using System;using System.CodeDom;using System.CodeDom.Compiler;using System.Collections.Generic;using System.Linq;using System.Reflection;using System.Text;using Microsoft.CSharp;namespace ConsoleApplication1{    class Program    {        static void Main(string[] args)        {            List<string> ExpList = new List<string>()            {                "23 + 56 * 2",                "Math.Pow(2, 2)",                "Math.Pow(2, 0.5)",                "(3 + 5) * 2 - 7",                "1.0 / 3.0 + 7",                "((2 + 5) * 2 + (4 * 50)) * 30 - 1",                "-10 * 10 - 9",                "2 / 10.0 - 4",                "3.14 * 3.14 * 2",                "2 << 4"            };            ExpList.ForEach(i => Console.WriteLine(i + " = " + ExpCalc.Calc(i)));            string expwithvar = "(@a + @b) * 10";            double rexpwithvar = ExpCalc.Calc(expwithvar, new Tuple<string, string>("a", "10"), new Tuple<string, string>("b", "5"));            Console.WriteLine(rexpwithvar);/*output:23 + 56 * 2 = 135Math.Pow(2, 2) = 4Math.Pow(2, 0.5) = 1.4142135623731(3 + 5) * 2 - 7 = 91.0 / 3.0 + 7 = 7.33333333333333((2 + 5) * 2 + (4 * 50)) * 30 - 1 = 6419-10 * 10 - 9 = -1092 / 10.0 - 4 = -3.83.14 * 3.14 * 2 = 19.71922 << 4 = 32150*/        }    }    class ExpCalc    {        private static Random rnd = new Random();        private static string RandomString(string CharList = "abcdefghijklmnopqrstuvwxyz", int length = 1)        {            string rndstr = "";            for (int i = 1; i <= length; i++)            {                rndstr += CharList.Substring(rnd.Next(0, CharList.Length), 1);            }            return rndstr;        }        private static string RenderText(string Template, Dictionary<string, string> Params)        {            string result = Template;            foreach (var item in Params)            {                result = result.Replace("@" + item.Key, item.Value);            }            return result;        }        public static double Calc(string exp)        {            CSharpCodeProvider provider = new CSharpCodeProvider();            CompilerParameters cps = new CompilerParameters();            cps.GenerateExecutable = false;            cps.GenerateInMemory = true;            string classSource = "using System;\n" +                                "class @classname\n" +                                "{\n" +                                "\tpublic double Eval { get { return @exp; } } \n" +                                "}";            Dictionary<string, string> renderparams = new Dictionary<string, string>();            string classname = RandomString(length: 10);            renderparams.Add("classname", classname);            renderparams.Add("exp", exp);            classSource = RenderText(classSource, renderparams);            CompilerResults result = provider.CompileAssemblyFromSource(cps, classSource);            Assembly assembly;            try            {                assembly = result.CompiledAssembly;            }            catch            {                throw new Exception("Invaild expression: " + exp);            }            object calcobj = assembly.CreateInstance(classname);            PropertyInfo pi = calcobj.GetType().GetProperty("Eval");            double returnvar = 0.0f;            returnvar = Convert.ToDouble(pi.GetValue(calcobj, null));            return returnvar;        }        public static double Calc(string exp, params Tuple<string, string>[] varlist)        {            double result = 0.00;            Dictionary<string, string> dict = new Dictionary<string, string>();            foreach (var i in varlist.AsEnumerable())            {                dict.Add(i.Item1, i.Item2);            }            exp = RenderText(exp, dict);            result = Calc(exp);            return result;        }    }}

 

0 0