取自
friend of mine's blog
:
CSharpCodeProvider codeProvider = new CSharpCodeProvider();
codeProvider.GenerateCodeFromNamespace(codeNamespace, new StringWriter(), new CodeGeneratorOptions());
CompilerParameters param = new CompilerParameters(assemblyReferences);
param.GenerateExecutable = false;
param.GenerateInMemory = true;
param.TreatWarningsAsErrors = false;
param.WarningLevel = 4;
CompilerResults results = codeProvider.CompileAssemblyFromDom(param, compileUnit);
Assembly assembly = results.CompiledAssembly;
Type[] types = assembly.GetExportedTypes();
然后,可以对类型使用反射来创建所需类型的实例,并执行所需的任何方法。