2008-08-07 8 views

답변

7

CompileAssemblyFromDom은 .cs 파일로 컴파일 된 다음 정상적인 C# 컴파일러를 통해 실행됩니다.

예 :

A (지금은 존재하지 않는) 임시 파일에 오류를 표시
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 : \ 문서 및 설정 \ 야곱 \ 로컬 설정 \ 온도 \ x59n9yb- .0.cs : 17

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

잘못된 표현식 ' x59n9yb-.0.cs : 17

그래서 나는 대답은 실망 불구하고, "아니오"

+0

가 절대적으로 올바른 것 같다. CodeDOM은 C# 텍스트로 변환되어 임시 파일로 저장되고 C++ (C++로 개발 됨) 컴파일러가 호출됩니다. 이것이 Mono의 경우인지는 모르지만, 아쉽게도 CodeDOM은 C#을 직접 작성하는 것보다 속도가 실제로 느립니다. –

+0

아마도 csc.exe는 C#으로 다시 작성되기 때문에 나중에 AST를 컴파일러에 직접 전달할 수있는 관리 방법이있을 수 있습니다. 그러나 .NET 3.5가 현재로 서 있기 때문에 현재 IL 어셈블리 또는 바이트 코드를 직접 내보내는 것 외에는 컴파일러 프론트 엔드를 우회 할 방법이 없습니다. –

0

필자는 궁극적 인 컴파일러 호출을 먼저 찾았으며 포기했습니다. 인내심을 가지기 위해 꽤 많은 수의 인터페이스 레이어와 가상 클래스가 있습니다.

컴파일러의 소스 리더 부분이 DOM 트리로 끝나지 않을 것이라고 생각하지만 직관적으로 나는 당신과 동의 할 것입니다. DOM을 IL로 변환하는 데 필요한 작업은 C# 소스 코드를 읽는 것보다 훨씬 적어야합니다.