动态编译是:Parse,序列化是:ToJsonString,需要关注的点是:动态编译时,需要引用相关的.NET运行时DLL,而这些DLL必需在工具的根目录下,否则可能导致引用找不到DLL导致编译失败,故项目中引用了常见的几个DLL,并设置了复制到输出目录中,如果后续有用到其它特殊的类型同样参照该方法先把DLL包含到项目中,并设置复制到输出目录中,然后在动态编译代码中使用cp.ReferencedAssemblies.Add("XXXX.dll");进行添加。核心代码如下:
private List<string> Parse(string csCode) { var provider = new CSharpCodeProvider(); var cp = new CompilerParameters(); cp.GenerateExecutable = false; cp.GenerateInMemory = true; cp.IncludeDebugInformation = false; //cp.ReferencedAssemblies.Add("mscorlib.dll"); cp.ReferencedAssemblies.Add("System.dll"); cp.ReferencedAssemblies.Add("System.Data.dll"); cp.ReferencedAssemblies.Add("System.Linq.dll"); cp.ReferencedAssemblies.Add("System.ComponentModel.DataAnnotations.dll"); cp.ReferencedAssemblies.Add("Newtonsoft.Json.dll"); CompilerResults result = provider.CompileAssemblyFromSource(cp, csCode); List<string> errList = new List<string>(); if (result.Errors.Count > 0) { foreach (CompilerError err in result.Errors) { errList.Add(string.Format("Line:{0},ErrorNumber:{1},ErrorText:{2}", err.Line, err.ErrorNumber, err.ErrorText)); } MessageBox.Show("Compile error:\n" + string.Join("\n", errList)); return null; } dyAssembly = result.CompiledAssembly; return dyAssembly.GetTypes().Select(t => t.FullName).ToList(); } private string ToJsonString(string targetType) { if (dyAssembly == null) { MessageBox.Show("dyAssembly is null!"); return null; } var type = dyAssembly.GetType(targetType); var typeConstructor = type.GetConstructor(Type.EmptyTypes); var obj = typeConstructor.Invoke(null); return JsonConvert.SerializeObject(obj, Formatting.Indented, new JsonSerializerSettings { DateFormatString = "yyyy-MM-dd HH:mm:ss" }); }