2016-08-24 32 views
1

我正在使用Roslyn API來生成和編譯類。生成的類看起來是這樣的:Roslyn - 編譯簡單類:「無法找到類型或名稱空間名稱字符串...」

namespace MyCompany.Product 
{ 
    public class TestClass 
    { 
     public void Configure(string id) 
     { 
     } 
    } 
} 

然而,當我來到編譯它,所述發送(TED)結果給出:

錯誤CS0246:類型或命名空間名稱「字符串」不能找到(是否缺少using指令或程序集引用?)

這裏是進行編譯的方法:

private static readonly IEnumerable<string> DefaultNamespaces = new[] 
     { 
      "System", 
      "System.IO", 
      "System.Net", 
      "System.Linq", 
      "System.Text", 
      "System.Text.RegularExpressions", 
      "System.Collections.Generic" 
     }; 

    public void Compile(IEnumerable<SyntaxTree> syntaxes, string targetPath) 
    { 

     var assemblyPath = Path.GetDirectoryName(typeof(object).Assembly.Location); 
     // assemblyPath = "C:\Windows\Microsoft.NET\Framework64\v4.0.30319" 

     IEnumerable<MetadataReference> defaultReferences = new[] 
     { 
      MetadataReference.CreateFromFile(Path.Combine(assemblyPath, "mscorlib.dll")), 
      MetadataReference.CreateFromFile(Path.Combine(assemblyPath, "System.dll")), 
      MetadataReference.CreateFromFile(Path.Combine(assemblyPath, "System.Core.dll")), 
      MetadataReference.CreateFromFile(Path.Combine(assemblyPath, "System.Runtime.dll")), 

     }; 
     CSharpCompilationOptions defaultCompilationOptions = new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary) 
        .WithOverflowChecks(true).WithOptimizationLevel(OptimizationLevel.Release) 
        .WithUsings(DefaultNamespaces); 

     CSharpCompilation compilation = CSharpCompilation.Create(
      targetPath, 
      syntaxTrees: syntaxes, 
      references: defaultReferences, 
      options: defaultCompilationOptions); 

     using (var ms = new MemoryStream()) 
     { 
      EmitResult result = compilation.Emit(ms); 
      // here, result.Success = false, with it's Diagnostics collection containing the error 
      if (!result.Success) 
      { 
      } 
     } 
    } 

但是,如果我編譯下面的類,但使用類型「字符串」的一個常數,它編譯如預期,因此方法參數類型聲明,當它不喜歡「串」:

namespace MyCompany.Product 
{ 
    public class TestClass 
    { 
     public const string Id = "e1a64bdc-936d-47d9-aa10-e8634cdd7070"; 
    } 
} 

我正在使用框架4.6.1,Microsoft.CodeAnalysis版本= 1.3.1.0

+0

嘗試添加到'.WithAssemblyIdentityComparer(DesktopAssemblyIdentityComparer.Default)'到'defaultCompilationOptions'。 – m0sa

+0

@ m0sa - 仍然無法使用該選項 – PhatBuck

回答

2

我餵你的第一個例子片段CSharpSyntaxTree.ParseText和結果到Compile - 它按預期成功編譯。

我的猜測是你正在編譯的節點類型在某種程度上是錯誤的。 string是一個C#關鍵字,用於別名System.String類型,本身不是類型名稱。

您可以使用Roslyn Syntax Visualizer檢查自己的SyntaxTreeCSharpSyntaxTree.ParseText根據預期輸出產生的差異。

+0

非常感謝。我按照你的建議檢查了我的SyntaxTree,並將它與Syntax Visualizer進行了比較。果然我注意到了一個區別。我正在使用'.WithType(SyntaxFactory.IdentifierName(「string」))'而不是'.WithType(SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.StringKeyword)))''。這現在按預期工作 – PhatBuck

相關問題