- Roslyn Cookbook
- Manish Vasani
- 226字
- 2021-07-15 17:07:32
How to do it...
- In Solution Explorer, double-click on the Resources.resx file in CSharpAnalyzers project to open the resource file in the resource editor.
- Replace the existing resource strings for AnalyzerDescription, AnalyzerMessageFormat and AnalyzerTitle with new strings.

- Replace the Initialize method implementation with the following:
public override void Initialize(AnalysisContext context)
{
context.RegisterSyntaxTreeAction(syntaxTreeContext =>
{
// Iterate through all statements in the tree.
var root = syntaxTreeContext.Tree.GetRoot(syntaxTreeContext.CancellationToken);
foreach (var statement in root.DescendantNodes().OfType<StatementSyntax>())
{
// Skip analyzing block statements.
if (statement is BlockSyntax)
{
continue;
}
// Report issue for all statements that are nested within a statement,
// but not a block statement.
if (statement.Parent is StatementSyntax && !(statement.Parent is BlockSyntax))
{
var diagnostic = Diagnostic.Create(Rule, statement.GetFirstToken().GetLocation());
syntaxTreeContext.ReportDiagnostic(diagnostic);
}
}
});
}
- Click on Ctrl + F5 to start a new Visual Studio instance with the analyzer enabled.
- In the new Visual Studio instance, create a new C# class library with the following code:
namespace ClassLibrary
{
public class Class1
{
void Method(bool flag, int value)
{
while (flag)
if (value > 0)
System.Console.WriteLine(value);
}
}
}
- Verify the analyzer diagnostic is neither reported for the method block for Method nor the while statement, but is reported for the if statement and System.Console.WriteLine invocation statement:

- Now, add curly braces around the System.Console.WriteLine invocation statement and verify the only single warning is now reported for the if statement:

推薦閱讀
- Objective-C Memory Management Essentials
- OpenDaylight Cookbook
- Learning Real-time Processing with Spark Streaming
- Building a Game with Unity and Blender
- HTML5+CSS3基礎開發教程(第2版)
- oreilly精品圖書:軟件開發者路線圖叢書(共8冊)
- 編寫高質量代碼:改善C程序代碼的125個建議
- Quarkus實踐指南:構建新一代的Kubernetes原生Java微服務
- Android項目實戰:手機安全衛士開發案例解析
- LabVIEW虛擬儀器程序設計從入門到精通(第二版)
- Laravel Application Development Blueprints
- 征服C指針(第2版)
- 數據結構與算法詳解
- C#教程
- Java語言程序設計與實現(微課版)