2

(我找不到合适的标题)

我需要使用 C# CodeDomProvider 来编译几个文件,每个文件都包含一个类。我编写了一个“生成器”类,其中包含所述提供者(以及其他东西),它被调用来处理每个文件。我不能在这里跳过整个代码,但相关部分是:

    private Assembly CompileFile(string _file)
    {
        CodeDom provider = CodeDomProvider.CreateProvider("CSharp");
        CompilerParameters cparams = new CompilerParameters();
        cparams.GenerateExecutable = false;
        cparams.GenerateInMemory = true;
        cparams.ReferencedAssemblies.Add (/*assembly containing attributes classes */ assemblyReference);
        cparams.OutputAssembly =  "outputAssembly"; // Required to be able to compile more than one file with the same provider, for some reason
        CompilerResults results = provider.CompileAssemblyFromFile(_file);
        if (results.Errors.HasErrors)
        {
            StringBuilder errors = new StringBuilder("Compiler Errors :\r\n");
            foreach (CompilerError error in results.Errors )
            {
                errors.AppendFormat("Line {0},{1}\t: {2}\n", error.Line, error.Column, error.ErrorText);
            }
            throw new Exception(errors.ToString());
        }

        return results.CompiledAssembly;
    }

在另一种方法中:

Assembly asm = CompileFile(_file);
foreach (Type t in asm.GetTypes())
  Console.WriteLine (t.ToString ());

如果此代码在同一个生成器类中被调用两次,asm.GetTypes() 将只返回第一个编译的类型,而不是第二个。我还尝试以相同的结果重新实例化提供程序和编译参数。我还尝试重新实例化整个生成器类,同样的问题。编译期间不会抛出异常。

我可能做错什么?

4

0 回答 0