- Roslyn Cookbook
- Manish Vasani
- 324字
- 2021-07-15 17:07:31
How to do it...
- In Solution Explorer, double-click on 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.RegisterSyntaxNodeAction(syntaxNodeContext =>
{
// Find implicitly typed variable declarations.
// Do not flag implicitly typed declarations that declare more than one variables,
// as the compiler already generates error CS0819 for those cases.
var declaration = (VariableDeclarationSyntax)syntaxNodeContext.Node;
if (!declaration.Type.IsVar || declaration.Variables.Count != 1)
{
return;
}
// Do not flag variable declarations with error type or special System types, such as int, char, string, and so on.
var typeInfo = syntaxNodeContext.SemanticModel.GetTypeInfo(declaration.Type, syntaxNodeContext.CancellationToken);
if (typeInfo.Type.TypeKind == TypeKind.Error || typeInfo.Type.SpecialType != SpecialType.None)
{
return;
}
// Report a diagnostic.
var variable = declaration.Variables[0];
var diagnostic = Diagnostic.Create(Rule, variable.GetLocation(), variable.Identifier.ValueText);
syntaxNodeContext.ReportDiagnostic(diagnostic);
},
SyntaxKind.VariableDeclaration);
}
- 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
{
public void M(int param1, Class1 param2)
{
// Explicitly typed variables - do not flag.
int local1 = param1;
Class1 local2 = param2;
}
}
}
- Verify the analyzer diagnostic is not reported in the error list for explicitly typed variables.
- Now, add the following implicitly typed variable declarations to the method:
// Implicitly typed variable with error type - do not flag.
var local3 = UndefinedMethod();
// Implicitly typed variable with special type - do not flag.
var local4 = param1;
- Verify the analyzer diagnostic is not reported in the error list for implicitly typed variables with error type or special type.
- Add the violating implicitly typed variable declaration to the method:
// Implicitly typed variable with user defined type - flag.
var local5 = param2;
- Verify the analyzer diagnostic is reported for this implicitly typed variable:

推薦閱讀
- VMware View Security Essentials
- Objective-C Memory Management Essentials
- Learn to Create WordPress Themes by Building 5 Projects
- PostgreSQL技術內幕:事務處理深度探索
- MySQL 8 DBA基礎教程
- Python高級編程
- Java EE 7 Performance Tuning and Optimization
- Visual C#通用范例開發金典
- C/C++數據結構與算法速學速用大辭典
- Spring Boot+MVC實戰指南
- 深入實踐C++模板編程
- Learning VMware vCloud Air
- Mastering Android Application Development
- MATLAB/Simulink與過程控制系統仿真
- Java程序員面試筆試真題庫