[英]Console.WriteLine text from CodeDomProvider
I'm trying to use CodeDomProvider to make a C# compiler. 我正在尝试使用CodeDomProvider制作C#编译器。 I managed to get the errors but i can't get the output.
我设法得到错误,但我无法获得输出。
This is what i have so far: 这是我到目前为止所拥有的:
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
is the class that contains the functions from above 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
is always empty. compilerResults.Output
始终为空。 If i run this piece of code: 如果我运行这段代码:
using System;
public class HelloWorld
{
public static void Main()
{
Console.WriteLine("Hello world!");
}
}
What can i do to display the message "Hello world!"? 如何显示消息“ Hello world!”?
CompileAssemblyFromSource
creates, as its name implies, an assembly. 顾名思义,
CompileAssemblyFromSource
创建一个程序集。 To get access to the compiled code, you can use the CompilerResults.CompiledAssembly
property and then use reflection to find and invoke the Main
method: 要访问已编译的代码,可以使用
CompilerResults.CompiledAssembly
属性 ,然后使用反射来查找和调用Main
方法:
compilerResults.CompiledAssembly.GetType("HelloWorld").GetMethod("Main").Invoke(null, null);
Though if you set parameters.GenerateExecutable
to true
, you can simplify this to: 虽然如果将
parameters.GenerateExecutable
设置为true
,则可以将其简化为:
compilerResults.CompiledAssembly.EntryPoint.Invoke(null, null);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.