C#使用CodeDom动态加载cs文件
public static object Create(string path) { var provOptions = new Dictionary<string, string>(); provOptions.Add("CompilerVersion", "v3.5"); CodeDomProvider codeDomProvider = new CSharpCodeProvider(provOptions); CompilerParameters compilerParameters = new CompilerParameters(); compilerParameters.GenerateExecutable = false; compilerParameters.GenerateInMemory = true; compilerParameters.ReferencedAssemblies.Add("mscorlib.dll"); compilerParameters.ReferencedAssemblies.Add("System.dll"); compilerParameters.ReferencedAssemblies.Add("System.Core.dll"); string[] code = new string[1]; code[0] = File.ReadAllText(path); CompilerResults compilerResults = codeDomProvider.CompileAssemblyFromSource(compilerParameters, code); Assembly ass = compilerResults.CompiledAssembly; var obj = ass.GetTypes().FirstOrDefault(); return Activator.CreateInstance(obj); }
一定要引用mscorlib,否则CodeDom编译出错