zoukankan      html  css  js  c++  java
  • c#动态计算表达式

    public class Expression
        {
            object instance;
            MethodInfo method;
            /// <summary>
            /// 表达试运算
            /// </summary>
            /// <param name="expression">表达试</param>
            public Expression(string expression)
            {
                if (expression.IndexOf("return") < 0) expression = "return " + expression + ";";
                string className = "Expression";
                string methodName = "Compute";
                CompilerParameters p = new CompilerParameters();
                p.GenerateInMemory = true;
                CompilerResults cr = new CSharpCodeProvider().CompileAssemblyFromSource(p, string.
                  Format("using System;sealed class {0}{{public double {1}(double x){{{2}}}}}",
                  className, methodName, expression));
                if (cr.Errors.Count > 0)
                {
                    string msg = "Expression("" + expression + ""): 
    ";
                    foreach (CompilerError err in cr.Errors)
                    { msg += err.ToString() + "
    "; }
                    throw new Exception(msg);
                }
                instance = cr.CompiledAssembly.CreateInstance(className);
                method = instance.GetType().GetMethod(methodName);
            }
            /// <summary>
            /// 处理数据
            /// </summary>
            /// <param name="x"></param>
            /// <returns>返回计算值</returns>
            public double Compute(double x)
            {
                return (double)method.Invoke(instance, new object[] { x });
            }
        }
    
        class Program
        {
            static void Main(string[] args)
            {
                Expression e = new Expression("x+5*9/3.2+6");
                Console.WriteLine(e.Compute(10));
                Console.Read();
            }
        }
  • 相关阅读:
    获取网页数据
    追踪公式引用的单元格
    loadRunner函数之lr_set_debug_message
    Python爬虫之抓取豆瓣影评数据
    Python爬虫之抓图
    loadRunner函数之web_add_header
    JVM是如何处理异常的
    1. JVM内存区块
    JVM-JVM是如何执行方法调用的
    JVM-内部类分析
  • 原文地址:https://www.cnblogs.com/highfly2012/p/6530392.html
Copyright © 2011-2022 走看看