如何将解决方案中的另一个项目(程序集)添加到编译器参数.引用程序集集



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

公共类 自定义类 : 接口类型

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

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 中,要么需要将程序集的完整路径添加到引用程序集位置。

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

最新更新