zoukankan      html  css  js  c++  java
  • (转)C# 自定义公式计算 字符串转换为计算公式,并得出计算结果

    • //方法一 利用DataTable中的Compute方法 例如:1*2-(4/1)+2*4=6    
    • string formulate = string.Format("{0}*{1} - {2}/{3} +{1}*{2}", 1, 2, 4, 1); 
    • DataTable dt = new DataTable(); 
    • Response.Write(dt.Compute(formulate, "").ToString()); 
    •  
    • Response.Write("<br/>"); 

     

    • //方法二  利用JS中强大的Eval函数 可以带if-else判断 添加COM引用:Microsoft Sctipt Control 1.0 
    • MSScriptControl.ScriptControl sc = new MSScriptControl.ScriptControlClass(); 
    • sc.Language = "JavaScript"
    • string formulate1 = string.Format("if({0}==2)((({0}*{1})-{3}+({1}*{2}))+{4}/{0});else(1+2*3)", 2, 3, 4, 5,6); 
    • object objResult = sc.Eval(formulate1); 
    • if (objResult != null
    •     Response.Write(objResult.ToString());//1+12+3 
    • /* 方法三 需将Microsoft.JScript 和Microsoft.Vsa加入参考并引用Microsoft.JScript */ 
    • publicobject EvalExpress(string sExpression) 
    •             Microsoft.JScript.Vsa.VsaEngine ve = Microsoft.JScript.Vsa.VsaEngine.CreateEngine(); 
    •             return Microsoft.JScript.Eval.JScriptEvaluate(sExpression, ve); 
    • }
  • 相关阅读:
    软件开发模式
    个人中心设计
    定制四则运算
    功能测试用例分析报告
    NABCD
    开发流程
    开发流程
    结对编程
    注册界面进行Toast提示
    登录注册页面修改错误
  • 原文地址:https://www.cnblogs.com/wadeheng/p/3083624.html
Copyright © 2011-2022 走看看