zoukankan      html  css  js  c++  java
  • c#字符串中包含的运算符按正常计算 例如按四则运算等,类似公式计算,很好很强大

        /// <summary>
        /// 将字符串中的运算符按正常计算 例如按四则运算
        /// </summary>
        /// <param name="expression">标准表达式如 1+15*0.5-200</param>
        /// <returns>返回计算的值,可以为任意合法的数据类型</returns>
        protected static object MathCalculate(string expression)
        {
            object retvar = null;
            Microsoft.CSharp.CSharpCodeProvider provider = new Microsoft.CSharp.CSharpCodeProvider();
            System.CodeDom.Compiler.CompilerParameters cp = new System.CodeDom.Compiler.CompilerParameters(
            new string[] { @"System.dll" });
            StringBuilder builder = new StringBuilder("using System;class CalcExp{public static object Calc(){ return \"expression\";}}");
            builder.Replace("\"expression\"", expression);
            string code = builder.ToString();
            System.CodeDom.Compiler.CompilerResults results;
            results = provider.CompileAssemblyFromSource(cp, new string[] { code });
            if (results.Errors.HasErrors)
            {
                retvar = null;
            }
            else
            {
                System.Reflection.Assembly a = results.CompiledAssembly;
                Type t = a.GetType("CalcExp");
                retvar = t.InvokeMember("Calc", System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.InvokeMethod
                    , System.Type.DefaultBinder, null, null);
            }
            return retvar;
        }

  • 相关阅读:
    Super Mario
    SPOJ Count on a tree
    SPOJ DQUERY
    51nod 区间中第K大的数
    POJ2104 K-th Number
    矩阵模板
    Sasha and Array
    MVC RenderSection
    Lazy Acquisition
    .net4.5 await async 简化之后的异步编程模型
  • 原文地址:https://www.cnblogs.com/smartsmile/p/6234410.html
Copyright © 2011-2022 走看看