|
以下是控制台应用程序。 请解答其中的问题。
public class Class1
{
public static List<string> ErrorMessage = new List<string>();
public static void Main()
{
string strCode = @"
using System;
public class Program
{
public void Main()
{
Console.WriteLine(""hello,man!"");
}
}
";
if (Compile(strCode))
{
//此处输出 hello,man! 该如何实现???
}
Console.ReadKey();
}
public static bool Compile(string source)
{
string ClassName = "Program";
CompilerParameters param = new CompilerParameters(new string[] { }, string.Empty, true);
param.TreatWarningsAsErrors = false;
param.GenerateExecutable = false;
param.IncludeDebugInformation = true;
CSharpCodeProvider provider = new CSharpCodeProvider();
CompilerResults result = provider.CompileAssemblyFromSource(param, new string[] { source });
string Message = "";
ErrorMessage.Clear();
if (!result.Errors.HasErrors)
{
Type t = result.CompiledAssembly.GetType(ClassName);
if (t != null)
{
object o = result.CompiledAssembly.CreateInstance(ClassName);
//Note:此处获取不到任何值,因为 Main方法没有返回值,所以 Message为null
Message = (string)t.InvokeMember("Main", BindingFlags.Instance | BindingFlags.InvokeMethod | BindingFlags.Public | BindingFlags.Static, null, o, null);
}
return true;
}
foreach (CompilerError error in result.Errors)
{
if (error.IsWarning) continue;
ErrorMessage.Add("Error(" + error.ErrorNumber + ") - " + error.ErrorText + "\t\tLine:" + error.Line.ToString() + " Column:" + error.Column.ToString());
}
return false;
}
}
|
|