1.下载Roslyn的Visual Studio分析器模板插件(VS2015 或VS2017)
我后来查询到官方说明vs2017已经内嵌了此功能
Want to start developing in C# and Visual Basic? Download Visual Studio 2017, which has the latest features built-in. There are also prebuilt Azure VM images available with Visual Studio 2017 already installed.
Roslyn(https://github.com/dotnet/roslyn)
2.创建分析器
打开visual studio 2017 选择Extensibility中的
3.测试分析器
系统默认的分析器是一个检测类名不能使用小写的规则
private static void AnalyzeSymbol(SymbolAnalysisContext context) { // TODO: Replace the following code with your own analysis, generating Diagnostic objects for any issues you find var namedTypeSymbol = (INamedTypeSymbol)context.Symbol; // Find just those named type symbols with names containing lowercase letters. if (namedTypeSymbol.Name.ToCharArray().Any(char.IsLower)) { // For all such symbols, produce a diagnostic. var diagnostic = Diagnostic.Create(Rule, namedTypeSymbol.Locations[0], namedTypeSymbol.Name); context.ReportDiagnostic(diagnostic); } }
运行F5,系统回新建一个vs副本窗口,我们新建一个consoleapp应用程序,
我们可以在分析器项目中设置断点,查看具体的运行效果,如我手动改Program为Program2,分析器就会侦测到改动,运行分析器代码,具体断点效果如下:
总结:
官方已经提供了一个完整的机遇Roslyn的代码分析器自定义模板;
我们需要新建基于此模板的分析器程序就可以了;
我们可以根据公司的项目规定按指定的规则设计代码分析器规则;
参考:C# and Visual Basic - Use Roslyn to Write a Live Code Analyzer for Your API