繁体   English   中英

来自CodeDomProvider的Console.WriteLine文本

[英]Console.WriteLine text from CodeDomProvider

我正在尝试使用CodeDomProvider制作C#编译器。 我设法得到错误,但我无法获得输出。

这是我到目前为止所拥有的:

    public List<string> Errors(CompilerResults compilerResults)
    {
        List<string> messages = new List<string>();

        foreach (CompilerError error in compilerResults.Errors)
        {
            messages.Add(String.Format("Line {0} Error No:{1} - {2}", error.Line, error.ErrorNumber, error.ErrorText));
        }

        return messages;
    }

    public CompilerResults ProcessCompilation(string programText)
    {
        CodeDomProvider codeDomProvider = CodeDomProvider.CreateProvider("CSharp");
        CompilerParameters parameters = new CompilerParameters();
        parameters.GenerateExecutable = false;
        StringCollection assemblies = new StringCollection();
        return codeDomProvider.CompileAssemblyFromSource(parameters, programText);
    }

CSharpCompiler是包含上述功能的类

    public JsonResult Compiler(string code)
    {
        CSharpCompiler compiler = new CSharpCompiler();
        CompilerResults compilerResults = compiler.ProcessCompilation(code);

        Debug.WriteLine("OUTPUT----------------------------------------------");
        foreach (var o in compilerResults.Output)
        {
            Debug.WriteLine(o);
        }

        List<string> compilerErrors = compiler.Errors(compilerResults);

        if (compilerErrors.Count != 0)
            return Json(new { success = false, errors = compilerErrors});

        return Json(true);
    }

compilerResults.Output始终为空。 如果我运行这段代码:

using System;

public class HelloWorld
{
    public static void Main()
    {
        Console.WriteLine("Hello world!");
    }
}

如何显示消息“ Hello world!”?

顾名思义, CompileAssemblyFromSource创建一个程序集。 要访问已编译的代码,可以使用CompilerResults.CompiledAssembly属性 ,然后使用反射来查找和调用Main方法:

compilerResults.CompiledAssembly.GetType("HelloWorld").GetMethod("Main").Invoke(null, null);

虽然如果将parameters.GenerateExecutable设置为true ,则可以将其简化为:

compilerResults.CompiledAssembly.EntryPoint.Invoke(null, null);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM