// 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 IEval { TT Eval(TT[] args); } public class DynEval { private static int n = 0; private static Regex re = new Regex(@"(\{)(\d+)(\})", RegexOptions.Compiled); private static Dictionary> m = new Dictionary>(); private static string KeyGen(string expr, string tn) { return expr + "#" + tn; } public static object Eval(string expr, params T[] args) { string tn = typeof(T).Name; IEval o; if(m.ContainsKey(KeyGen(expr, tn))) { o = m[KeyGen(expr, tn)]; } else { n++; string cn = "C" + n; string expexpr = re.Replace(expr, "args[$2]"); string src = "using System;" + "using E;" + "" + "public class " + cn + " : IEval<" + tn + ">" + "{" + " public " + tn + " Eval(" + tn + "[] args)" + " {" + " return " + expexpr + ";" + " }" + "}"; //Console.WriteLine(src); 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); //foreach(CompilerError ce in res.Errors) //{ // Console.WriteLine(ce.ToString()); //} Assembly asm = res.CompiledAssembly; o = (IEval)asm.CreateInstance(cn); m.Add(KeyGen(expr, tn), o); } return o.Eval(args); } } public class MainClass { public static void Main(string[] args) { Console.WriteLine(DynEval.Eval("{0}+{1}", 1, 2)); Console.WriteLine(DynEval.Eval("{0}+{1}", 3, 4)); Console.WriteLine(DynEval.Eval("({0}*{1}+{2})/{3}", 5, 4, 1, 2)); Console.WriteLine(DynEval.Eval("{0}+{1}", 1.2, 3.4)); Console.WriteLine(DynEval.Eval("{0}+{1}", "AB", "CD")); } } }