CSharpCodeProvider编译性能

时间:2020-03-05 18:38:18  来源:igfitidea点击:

是CompileAssemblyFromDom比CompileAssemblyFromSource快吗?

大概是因为它绕过了编译器前端。

解决方案

回答

我试图尽早找到最终的编译器调用,但我放弃了。为了我的耐心,有很多层接口和虚拟类。

我不认为编译器的源阅读器部分会以DOM树结尾,但是直觉上我会同意观点。将DOM转换为IL所需的工作应该比阅读C源代码少得多。

回答

CompileAssemblyFromDom编译为一个.cs文件,然后该文件通过普通的Ccompiler运行。

例子:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.CSharp;
using System.CodeDom;
using System.IO;
using System.CodeDom.Compiler;
using System.Reflection;

namespace CodeDomQuestion
{
    class Program
    {

        private static void Main(string[] args)
        {
            Program p = new Program();
            p.dotest("C:\fs.exe");
        }

        public void dotest(string outputname)
        {
            CSharpCodeProvider cscProvider = new CSharpCodeProvider();
            CompilerParameters cp = new CompilerParameters();
            cp.MainClass = null;
            cp.GenerateExecutable = true;
            cp.OutputAssembly = outputname;

            CodeNamespace ns = new CodeNamespace("StackOverflowd");

            CodeTypeDeclaration type = new CodeTypeDeclaration();
            type.IsClass = true;
            type.Name = "MainClass";
            type.TypeAttributes = TypeAttributes.Public;

            ns.Types.Add(type);

            CodeMemberMethod cmm = new CodeMemberMethod();
            cmm.Attributes = MemberAttributes.Static;
            cmm.Name = "Main";
            cmm.Statements.Add(new CodeSnippetExpression("System.Console.WriteLine('f'zxcvv)"));
            type.Members.Add(cmm);

            CodeCompileUnit ccu = new CodeCompileUnit();
            ccu.Namespaces.Add(ns);

            CompilerResults results = cscProvider.CompileAssemblyFromDom(cp, ccu);

            foreach (CompilerError err in results.Errors)
                Console.WriteLine(err.ErrorText + " - " + err.FileName + ":" + err.Line);

            Console.WriteLine();
        }
    }
}

它显示(现在不存在)临时文件中的错误:

) expected - c:\Documents and Settings\jacob\Local Settings\Temp\x59n9yb-.0.cs:17
  
  ; expected - c:\Documents and Settings\jacob\Local Settings\Temp\x59n9yb-.0.cs:17
  
  Invalid expression term ')' - c:\Documents and Settings\jacob\Local Settings\Tem p\x59n9yb-.0.cs:17

所以我想答案是"不"