C#.NET 動態計算運算式值

來源:互聯網
上載者:User

 

using System;
using System.CodeDom.Compiler;
using Microsoft.CSharp;
using System.Reflection;

namespace Pub.Class {
/// <summary>
/// 處理表達試運算---動態產生數學運算式並計算其值
/// 運算式使用 C# 文法,可帶一個的自變數(x)。
/// 運算式的自變數和值均為(double)類型。
/// </summary>
/// <example>
/// <code>
/// Expression expression = new Expression("Math.Sin(x)");
/// Console.WriteLine(expression.Compute(Math.PI / 2));
/// expression = new Expression("double u = Math.PI - x;" +
/// "double pi2 = Math.PI * Math.PI;" +
/// "return 3 * x * x + Math.Log(u * u) / pi2 / pi2 + 1;");
/// Console.WriteLine(expression.Compute(0));
///
/// Expression expression = new Expression("return 10*(5+5)/10;");
/// Response.Write(expression.Compute(0));
/// Response.End();
/// </code>
/// </example>
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 + "\"): \n";
foreach (CompilerError err in cr.Errors) msg += err.ToString() + "\n";
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 });
}
}
}

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.