• 程序集 动态编译运行C#代码


     点击按钮执行代码

          textOutput.Background = Brushes.White;
          var driver = new CodeDriverInAppDomain();
          bool isError;
          textOutput.Text = driver.CompileAndRun(textCode.Text, out isError);
          if (isError)
          {
            textOutput.Background = Brushes.Red;
          }

    CompileAndRun的代码

        public string CompileAndRun(string code, out bool hasError)
        {
          AppDomain codeDomain = AppDomain.CreateDomain("CodeDriver");
    
          CodeDriver codeDriver = (CodeDriver)
                codeDomain.CreateInstanceAndUnwrap("DynamicAssembly",
                      "Wrox.ProCSharp.Assemblies.CodeDriver");
    
          string result = codeDriver.CompileAndRun(code, out hasError);
    
          AppDomain.Unload(codeDomain); 
    
          return result;
        }
      public class CodeDriver : MarshalByRefObject
      {
        private string prefix =
           "using System;" +
           "public static class Driver" +
           "{" +
           "   public static void Run()" +
           "   {";
    
        private string postfix =
           "   }" +
           "}";
    
    
        public string CompileAndRun(string input, out bool hasError)
        {
          hasError = false;
          string returnData = null;
    
          CompilerResults results = null;
          using (var provider = new CSharpCodeProvider())
          {
            var options = new CompilerParameters();
            options.GenerateInMemory = true;
    
            var sb = new StringBuilder();
            sb.Append(prefix);
            sb.Append(input);
            sb.Append(postfix);
    
            results = provider.CompileAssemblyFromSource(options, sb.ToString());
          }
    
          if (results.Errors.HasErrors)
          {
            hasError = true;
            var errorMessage = new StringBuilder();
            foreach (CompilerError error in results.Errors)
            {
              errorMessage.AppendFormat("{0} {1}", error.Line, error.ErrorText);
            }
            returnData = errorMessage.ToString();
          }
          else
          {
            TextWriter temp = Console.Out;
            var writer = new StringWriter();
            Console.SetOut(writer);
            Type driverType = results.CompiledAssembly.GetType("Driver");
    
            driverType.InvokeMember("Run", BindingFlags.InvokeMethod |
                  BindingFlags.Static | BindingFlags.Public,
                  null, null, null);
            
            Console.SetOut(temp);
    
            returnData = writer.ToString();
          }
    
          return returnData;
        }
      }

    还可参考

    https://www.cnblogs.com/nanfei/p/6046128.html

  • 相关阅读:
    SetWindowsHookEx详解
    C#使用全局钩子(hook),SetWindowsHookEx返回0、不回调的解决
    C#使用全局钩子(hook),SetWindowsHookEx返回0、不回调的解决
    how to get geometry type of layer using IMapServer3 and IMapLayerInfo? (C#)
    how to get geometry type of layer using IMapServer3 and IMapLayerInfo? (C#)
    windows cmd命令显示UTF8设置
    windows cmd命令显示UTF8设置
    C#写的NoSQL开源项目/系统(系列)
    TCP协议详解(2)
    红黑树
  • 原文地址:https://www.cnblogs.com/noigel/p/14472766.html
Copyright © 2020-2023  润新知