// Collection of code snippets by Arne Vajhøj // (likely posted to comp.os.vms/INFO-VAX, INFO-TPU, MACRO32, eksperten.dk, newz.dk, LinkedIn or other place sometime between 1990 and now) using System; using System.Collections.Generic; using System.Text.RegularExpressions; using System.Reflection; using System.CodeDom.Compiler; using Microsoft.CSharp; namespace E { public interface IFuncEval { double Eval(double x); } public class FuncEvalFactory { private static int n = 0; private static Dictionary m = new Dictionary(); public static IFuncEval Create(string expr) { IFuncEval o = null; if(m.ContainsKey(expr)) { o = m[expr]; } else { n++; string cn = "FuncEval_" + n; string src = "using System;" + "using E;" + "" + "public class " + cn + " : IFuncEval" + "{" + " public double Eval(double x)" + " {" + " return " + expr + ";" + " }" + "}"; CodeDomProvider comp = new CSharpCodeProvider(); CompilerParameters param = new CompilerParameters(); param.GenerateInMemory = true; param.ReferencedAssemblies.Add("System.dll"); param.ReferencedAssemblies.Add(Assembly.GetExecutingAssembly().Location); CompilerResults res = comp.CompileAssemblyFromSource(param, src); Assembly asm = res.CompiledAssembly; o = (IFuncEval)asm.CreateInstance(cn); m.Add(expr, o); } return o; } } public class MainClass { public static void Test(string expr) { Console.WriteLine(expr + ":"); IFuncEval f = FuncEvalFactory.Create(expr); for(int i = -2; i <= 2; i++) { Console.WriteLine(" " + i + " -> " + f.Eval(i)); } } public static void Main(string[] args) { Test("2*x*x-3*x+4"); Test("Math.Exp(Math.Sqrt(x+2))"); } } }