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

C# 如何将解决方案中的另一个项目(程序集)添加到CompilerParameters.ReferencedAssembly集中?,c#,codedom,C#,Codedom,假设我在主项目中编译了一系列代码,如下所示。但是我想在CustomClass中实现一个接口。执行此操作时,该接口位于解决方案中的另一个项目中(主项目中的部分引用) 公共类CustomClass:InterfaceType 我犯了这样的错误。如何引用其他项目,以便在动态代码中使用接口和属于它的其他类 c:\Users\xxx\AppData\Local\Temp\m8ed4ow-.0.cs(1,32:错误CS0246:找不到类型或命名空间名称“InterfaceType”(是否缺少using指令或

假设我在主项目中编译了一系列代码,如下所示。但是我想在CustomClass中实现一个接口。执行此操作时,该接口位于解决方案中的另一个项目中(主项目中的部分引用)

公共类CustomClass:InterfaceType

我犯了这样的错误。如何引用其他项目,以便在动态代码中使用接口和属于它的其他类

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


底线是您需要将另一个项目添加到CompilerParameters.ReferencedAssemblys集合中。这可能很棘手,因为CodeDOM需要能够访问程序集,因此程序集需要位于GAC中,或者您需要将程序集的完整路径添加到ReferencedAssemblys位置


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

错误表示无效的
]
但是您的示例代码不包含此字符。也许您可以向我们展示
c:\Users\xxx\AppData\Local\Temp\nxplvi4d.0.cs
的内容。对不起,我添加了错误代码字符串的错误。我用上面编译的代码字符串的正确错误更新了帖子。
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");