2017-08-09 70 views
1

Roslyn文檔給出了下面的示例,作爲編譯某些代碼並顯示任何編譯錯誤的一種方式。Roslyn內存代碼的靜態代碼分析

我想知道是否有人知道在下面的例子中對變量sourceCode中包含的代碼執行一些靜態代碼分析的方法。我已經將StyleCop.Analyzers添加到了我的測試項目中,但在此階段我無法看到如何使用它來執行樣式分析(例如可讀性)。

使用StyleCop.Analyzers來做到這一點是否可行或者是否有其他方法?任何建議感激地收到。

謝謝。

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 
using Microsoft.CodeAnalysis; 
using Microsoft.CodeAnalysis.CSharp; 
using Microsoft.CodeAnalysis.CSharp.Syntax; 

namespace SemanticsCS 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      var sourceCode = @"using System; 
       using System.Collections.Generic; 
       using System.Text; 

       namespace HelloWorld 
       { 
        class Program 
        { 
         static void Main(string[] args) 
         { 
          Console.WriteLine(""Hello, World!""); 
         } 
        } 
       }"; 
      SyntaxTree tree = CSharpSyntaxTree.ParseText(sourceCode); 

      var root = (CompilationUnitSyntax)tree.GetRoot(); 
      var compilation = CSharpCompilation.Create("HelloWorld") 
               .AddReferences(
                MetadataReference.CreateFromFile(
                 typeof(object).Assembly.Location)) 
               .AddSyntaxTrees(tree); 

      using (var ms = new MemoryStream()) 
      { 
       EmitResult result = compilation.Emit(ms); 
       if (!result.Success) 
       { 
        IEnumerable<Diagnostic> failures = result.Diagnostics.Where(diagnostic => 
         diagnostic.IsWarningAsError || 
         diagnostic.Severity == DiagnosticSeverity.Error); 

        foreach (Diagnostic diagnostic in failures) 
        { 
         Console.WriteLine(diagnostic.ToString()); 
         Console.Error.WriteLine("{0}({1})", diagnostic.GetMessage(), diagnostic.Id); 
        } 
       } 
      } 
     } 
    } 
} 
+0

StyleCop.Analyzers是一套規則和分析你的項目代碼。當您嘗試編譯源代碼時,此規則會分析C#代碼。如果您查看'.csproj'文件並找到像這樣的'。因此StyleCop.Analyzers不能分析包含代碼的靜態或動態(sourceCode1 + sourceCode2)字符串。 –

+0

謝謝@GeorgeAlexandria – eslsys

回答

2

其實這是絕對有可能的。

您需要使用WithAnalyzers method將分析器引用添加到Roslyn Compilation

爲了做到這一點,您需要在項目中添加對StyleCop.Analy‌zers的正常引用,然後在其中創建各種DiagnosticAnalyzer的實例。由於他們是internal,你需要反思。

+0

這是非常有用的信息,因爲我不知道['CompilationWithAnalyzers'](http://source.roslyn.io/#Microsoft.CodeAnalysis/DiagnosticAnalyzer/CompilationWithAnalyzers.cs105),所以給了不正確的建議。謝謝。 –

+0

太棒了,非常感謝@Slaks - 像喬治我不知道CompilationWithAnalyzers,但覺得這肯定是可能的。 – eslsys