一个简易的C# 代码编译测试工具

TextEditor editor = new TextEditor();
public XtraFormCodeExector()
{
    InitializeComponent();
    editor.Text= "using System;\r\n"+
                    "namespace HelloWorld\r\n" +
                    "{\r\n" +
                        "\tclass Program\r\n" +
                        "\t{\r\n" +
                            "\t\tpublic static void Main()\r\n" +
                            "\t\t{\r\n" +
                                "\t\t\tConsole.WriteLine(\"aa\");\r\n" +
                            "\t\t}\r\n" +
                        "\t}\r\n" +
                    "}\r\n";

    //展示行号
    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();
    }
}

效果如下:

 

 

 

 

posted @ 2020-11-09 23:32  zhaogaojian  阅读(526)  评论(0编辑  收藏  举报