- 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:

推薦閱讀
- Google Apps Script for Beginners
- Learn Blockchain Programming with JavaScript
- R語言經典實例(原書第2版)
- Boost C++ Application Development Cookbook(Second Edition)
- Learning Chef
- Hands-On C++ Game Animation Programming
- INSTANT Passbook App Development for iOS How-to
- 領域驅動設計:軟件核心復雜性應對之道(修訂版)
- Java Web開發詳解
- JQuery風暴:完美用戶體驗
- 深入分析GCC
- 從零開始學Unity游戲開發:場景+角色+腳本+交互+體驗+效果+發布
- 軟件再工程:優化現有軟件系統的方法與最佳實踐
- Roslyn Cookbook
- jQuery基礎教程(第4版)