2008-08-07 108 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#源代码。