2008-08-07 106 views

回答

7

CompileAssemblyFromDom編譯爲一個.cs文件,然後通過普通的C#編譯器運行。

實施例:

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(); 
     } 
    } 
} 

,其示出了在(不存在現在)臨時文件錯誤:

)預期 - C:\ Documents和Settings \雅各布\本地設置的\ Temp \ x59n9yb- .0.cs:17

;預期 - c:\ Documents and Settings \ jacob \ Local Settings \ Temp \ x59n9yb-.0.cs:17

無效的表達式')' - c:\ Documents and Settings \ jacob \ Local Settings \ Tem p \ x59n9yb-.0.cs:17

所以我想答案是 「不」

+0

絕對正確的,儘管令人失望。 CodeDOM被轉換爲C#文本,保存到臨時文件,然後調用C#編譯器(用C++開發)。我不知道Mono是否是這種情況,但不幸的是,CodeDOM實際上比直接編寫C#要慢。 – 2009-11-20 16:15:12

0

我試過早些時候發現最終的編譯器調用,我放棄了。爲了我的耐心,有相當多的接口層和虛擬類。

我不認爲編譯器的源代碼閱讀器部分以DOM樹結束,但直觀上我會同意你的看法。將DOM轉換爲IL所需的工作應該遠遠少於閱讀C#源代碼。