zoukankan      html  css  js  c++  java
  • 一个简易的C# 代码编译测试工具

    TextEditor editor = new TextEditor();
    public XtraFormCodeExector()
    {
        InitializeComponent();
        editor.Text= "using System;
    "+
                        "namespace HelloWorld
    " +
                        "{
    " +
                            "	class Program
    " +
                            "	{
    " +
                                "		public static void Main()
    " +
                                "		{
    " +
                                    "			Console.WriteLine("aa");
    " +
                                "		}
    " +
                            "	}
    " +
                        "}
    ";
    
        //展示行号
        editor.ShowLineNumbers = true;
        editor.Padding = new System.Windows.Thickness(20);
        //字体
        editor.FontFamily = new System.Windows.Media.FontFamily("Console");
        editor.FontSize = 14;
        //C#语法高亮
        editor.SyntaxHighlighting = HighlightingManager.Instance.GetDefinition("C#");
        //将editor作为elemetnHost的组件
        elementHost1.Child = editor;
        System.Console.SetOut(new TextBoxWriter(textBoxOutPut));
    }
    
    private void simpleButtonExec_Click(object sender, EventArgs e)
    {
        // 编译器
        CodeDomProvider cdp = CodeDomProvider.CreateProvider("C#");
    
        // 编译器的参数
        CompilerParameters cp = new CompilerParameters();
        cp.ReferencedAssemblies.Add("System.dll");
        cp.ReferencedAssemblies.Add("System.Data.dll");
        cp.GenerateExecutable = false;
        cp.GenerateInMemory = true;
    
        //编译结果
        CompilerResults cr = cdp.CompileAssemblyFromSource(cp, HelloWorld(editor.Text));
    
        if (cr.Errors.HasErrors)
        {
            foreach (CompilerError item in cr.Errors)
            {
                string strInfo = string.Format("{0} {1}({2}:{3}):{4}", item.IsWarning ? "警告" : "错误", item.ErrorNumber, item.Line, item.Column, item.ErrorText);
                Console.WriteLine(strInfo);
            }
        }
        else
        {
            // 编译后的程序集
            Assembly ass = cr.CompiledAssembly;
            // 得到HelloWorld类中的Program方法
            Type type = ass.GetType("HelloWorld.Program");
            MethodInfo mi = type.GetMethod("Main");
    
            // 执行
            mi.Invoke(null, null);
        }
        // 动态构建的代码
        static string HelloWorld(string str)
        {
            StringBuilder sbCode = new StringBuilder();
            sbCode.Append(str);
            return sbCode.ToString();
        }
    }

    效果如下:

     

     

  • 相关阅读:
    前端面试题汇总
    前端学习计划汇总
    idea修改项目名导致无法找到主类
    idea run dashbord使用
    记git提交异常
    关于META-INF下的spring.factories文件
    lombok注解
    springcloud-ribbon&feign
    CAP定理
    git文件锁定不更新和忽略
  • 原文地址:https://www.cnblogs.com/zhaogaojian/p/13951667.html
Copyright © 2011-2022 走看看