日期:2014-05-17  浏览次数:20833 次

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;
    }