所用到的技术
示例代码
public static void Main(string[] args)
{
string test=@"
int MAX_N = 100;
int n = 10;
int i = 10;
int k = 10;
int l = 10;
return ((n == MAX_N) && (i < MAX_N))|((k == MAX_N) && (l < MAX_N));
";
string code = CodeBegin+test+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);
}
static string CodeBegin=@"
using System;
namespace RuntimeCompute
{
class JudgeCondition
{
public static bool GetValue()
{
";
static string CodeEnd=@"
}
}
}
";
}