В данном примере функция createDelegate получает некую пользовательскую строку с какой-либо функцией, значение которой нужно получить, подставляет эту строку в строку code, и компилирует в рантайме.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 | using System; using System.Reflection; using Microsoft.CSharp; using System.CodeDom.Compiler; class Script //singleton { private static Script instance; private Script() { } string code = @" using System; namespace UserFunctions { public class FunctionClass { public static int Function(int arg) { return script_func; } } } "; CSharpCodeProvider provider = new CSharpCodeProvider(); public static Script Instance { get { if (instance == null) { instance = new Script(); } return instance; } } public Func<int, int> createDelegate(string script) { try { string finalCode = code.Replace("script_func", script); CompilerResults results = provider.CompileAssemblyFromSource(new CompilerParameters(), finalCode); System.Type assembly = results.CompiledAssembly.GetType("UserFunctions.FunctionClass"); MethodInfo func = assembly.GetMethod("Function"); return (Func<int, int>)Delegate.CreateDelegate(typeof(Func<int, int>), func); } catch { throw new Exception(string.Format("ошибка в скрипте: {0}", script)); } } } |