官术网_书友最值得收藏!

How to do it...

  1. In Solution Explorer, double-click on Resources.resx file in CSharpAnalyzers project to open the resource file in the resource editor.
  2. Replace the existing resource strings for AnalyzerDescription, AnalyzerMessageFormat and AnalyzerTitle with new strings:
  1. 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);
}
  1. Click on Ctrl + F5 to start a new Visual Studio instance with the analyzer enabled.
  2. 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;
}
}
}
  1. Verify the analyzer diagnostic is not reported in the error list for explicitly typed variables.
  2. 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;
  1. Verify the analyzer diagnostic is not reported in the error list for implicitly typed variables with error type or special type.
  2. Add the violating implicitly typed variable declaration to the method:
 // Implicitly typed variable with user defined type - flag.
var local5 = param2;
  1. Verify the analyzer diagnostic is reported for this implicitly typed variable:
主站蜘蛛池模板: 扶沟县| 杭锦旗| 尚志市| 武威市| 丁青县| 开远市| 云梦县| 九台市| 威信县| 赣榆县| 三台县| 北宁市| 峨眉山市| 贵溪市| 兴仁县| 平邑县| 巴彦淖尔市| 杭锦后旗| 天柱县| 泾阳县| 沂水县| 上高县| 江油市| 西充县| 新龙县| 鄂托克前旗| 封丘县| 清丰县| 仙游县| 壤塘县| 昭觉县| 罗江县| 屏山县| 丽江市| 旺苍县| 惠安县| 武清区| 江达县| 荥阳市| 武平县| 家居|