using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.CSharp;
using System.CodeDom.Compiler;
using System.Reflection;
namespace ConsoleApplication1
{
class Program
{
static string CodeBegin = @"
using System;
namespace RuntimeCompute
{
class JudgeCondition
{
public static string GetValue()
{
";
static string CodeEnd = @"
}
}
}";
public static void Main(string[] args)
{
string myCode =
" " +"\r\n" +
" return \"Hello Workd!\" ; "+
" " + "\r\n";
string code = CodeBegin + myCode + CodeEnd;
//Console.WriteLine(code);
CSharpCodeProvider provider = new CSharpCodeProvider();
ICodeCompiler compiler = provider.CreateCompiler();
CompilerParameters param = new CompilerParameters();
param.ReferencedAssemblies.Add("System.dll");
param.GenerateExecutable = false;
param.GenerateInMemory = true;
CompilerResults cr = compiler.CompileAssemblyFromSource(param, code);
if (cr.Errors.HasErrors)
{
Console.WriteLine("编译错误:");
foreach (CompilerError err in cr.Errors)
Console.WriteLine(err.ErrorText);
}
else
{
Assembly assembly = cr.CompiledAssembly;
MethodInfo mi = assembly.GetType("RuntimeCompute.JudgeCondition").GetMethod("GetValue");
object value = mi.Invoke(null, null);
Console.WriteLine(value);
}
Console.ReadKey(true);
}
}
}