其中最后一个例子就是我在随笔“画函数图形的C#程序,兼论一个病态函数”的下列函数的计算结果:
[图片]// Expression.cs - 动态生成数学表达式并计算其值
[图片]// 表达式使用 C# 语法,可带一个的自变量(x)。
[图片]// 表达式的自变量和值均为(double)类型。
[图片]// 使用举例:
[图片]// 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));
[图片] [图片]using System;
[图片]using System.CodeDom.Compiler;
[图片]using Microsoft.CSharp;
[图片]using System.Reflection;
[图片]using System.Text;
[图片] [图片]namespace Skyiv.Util
[图片][图片][图片]{
[图片] sealed class Expression
[图片][图片] [图片]{
[图片] object instance;
[图片] MethodInfo method;
[图片] [图片] 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);
[图片] }
[图片] [图片] public double Compute(double x)
[图片][图片] [图片]{
[图片][图片] return (double)method.Invoke(instance, new object []
[图片]{ x });
[图片] }
[图片] }
[图片]}
[图片] 在这里向 CSDN 论坛的“LoveCherry(论成败,人生豪迈;大不了,重头再来!^_^) ”表示感谢,我的程序就是在他的程序的基础上发展而来的。