如何在 C# 中将声明与 CodeDomProvider 结合使用?

How to include using declaratives with CodeDomProvider in c#?

我想将几个 .cs 文件编译成一个可执行程序。 我的 CodeDomProvider 找不到我写入 .cs 文件的 using 声明。特别是创建了以下错误消息:

-The type- or namespace 'CodeDom' in the namespace 'System' is not available.
-The type- or namespace 'Windows' in the namespace 'System' is not available.
-The type- or namespace 'Stack' could not be found.

从这个函数,我正在调用 CodeDomProvider:

    private CompileParserSolution()
    {
        List<string> cSharpFiles = new List<string>();

        DirectoryInfo dir = new DirectoryInfo(Path.Combine(_inData.ProjectDir, @"NCParser\NCParser"));

        foreach (FileInfo f in dir.GetFiles("*.cs"))
        {
            cSharpFiles.Add(Path.Combine(dir.FullName, f.Name));
        }

        CodeDomProvider provider = CodeDomProvider.CreateProvider("CSharp");

        CompilerParameters cp = new CompilerParameters();
        cp.GenerateExecutable = true;
        cp.OutputAssembly = "Parser_TEST.exe";
        cp.GenerateInMemory = true;
        cp.TreatWarningsAsErrors = false;
        cp.ReferencedAssemblies.Add("System.Linq.dll");
        cp.ReferencedAssemblies.Add("System.Text.RegularExpressions.dll");
        cp.ReferencedAssemblies.Add(Path.Combine(_inData.ProjectDir, @"NCParser\NCParser", @"QUT.ShiftReduceParser.dll"));

        CompilerResults cr = provider.CompileAssemblyFromFile(cp, cSharpFiles.ToArray());
    }

我的问题是,如何将 System.CodeDomSystem.WindowsSystem.Collections.Stack 库包含到项目中进行编译。

使用命令:

        cs.ReferencedAssemblies.Add("System.CodeDom.dll");
        ...

没用!

程序集和命名空间彼此不对应1:1。要查找特定类型在哪个程序集中,请查看其 MSDN 文档。

  • 没有System.CodeDom.dll,很多CodeDOM类型都在System.dll里面,你没有引用。
  • Stack<T> 同样在 System.dll.
  • WPF 分布在多个程序集中,基本类型在 PresentationFramework.dll。

引用这些程序集可能会解决您的问题。