如何将我的解决方案中的另一个项目(程序集)添加到CompilerParameters.ReferencedAssemblies集?

假设我有一串代码,如下所示,我在主项目中编译。 但我想在CustomClass中实现一个接口。 界面位于我的解决方案中的另一个项目中(我的主项目中的部分引用)当我这样做时

公共类CustomClass:InterfaceType

我收到这样的错误。 如何在动态代码中引用其他项目以便我可以使用接口和其他类?

c:\ Users \ xxx \ AppData \ Local \ Temp \ m8ed4ow-.0.cs(1,32:错误CS0246:找不到类型或命名空间名称’InterfaceType’(您是否缺少using指令或程序集引用) ?)

string code2 = " public class CustomClass : InterfaceType " + " {" + " }"; // Compiler and CompilerParameters CSharpCodeProvider codeProvider = new CSharpCodeProvider(); CompilerParameters compParameters = new CompilerParameters(); compParameters.GenerateInMemory = false; //default //compParameters.TempFiles = new TempFileCollection(Environment.GetEnvironmentVariable("TEMP"), true); compParameters.IncludeDebugInformation = true; //compParameters.TempFiles.KeepFiles = true; compParameters.ReferencedAssemblies.Add("System.dll"); CodeDomProvider compiler = CSharpCodeProvider.CreateProvider("CSharp"); // Compile the code CompilerResults res = codeProvider.CompileAssemblyFromSource(compParameters, code2); // Check the compiler results for errors StringWriter sw = new StringWriter(); foreach (CompilerError ce in res.Errors) { if (ce.IsWarning) continue; sw.WriteLine("{0}({1},{2}: error {3}: {4}", ce.FileName, ce.Line, ce.Column, ce.ErrorNumber, ce.ErrorText); } string error = sw.ToString(); sw.Close(); // Create a new instance of the class 'CustomClass' object myClass = res.CompiledAssembly.CreateInstance("CustomClass"); 

底线是您需要将其他项目添加到CompilerParameters.ReferencedAssemblies集合中。 这可能很棘手,因为CodeDOM需要能够到达程序集,因此程序集需要在GAC中,或者您需要将程序集的完整路径添加到ReferencedAssemblies位置。

一种简单的方法,如果您在执行CodeDOM编译器的项目中引用包含“InterfaceType”的项目,则执行以下操作: compilerParameters.ReferencedAssemblies.Add(typeof(InterfaceType).Assembly.Location); 。 如果没有,您将不得不找出一些其他方法来确保CodeDOM可以找到您想要引用的程序集。