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);
}
}
}
}
}
}
StyleCop.Analyzers是一套规则和分析你的项目代码。当您尝试编译源代码时,此规则会分析C#代码。如果您查看'.csproj'文件并找到像这样的 '。因此StyleCop.Analyzers不能分析包含代码的静态或动态(sourceCode1 + sourceCode2)字符串。 –
谢谢@GeorgeAlexandria – eslsys