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

  • Roslyn Cookbook
  • Manish Vasani
  • 230字
  • 2021-07-15 17:07:32

How it works...

Syntax node analyzers register one or more syntax node action callbacks to analyse syntax kinds of interest. We specified interest in analyzing VariableDeclaration syntax kind in the RegisterSyntaxNodeAction invocation.

 

context.RegisterSyntaxNodeAction(syntaxNodeContext =>
{
...
}, SyntaxKind.VariableDeclaration);

Analysis works by operating on the syntax node and semantic model exposed off the syntax node analysis context in the callback. We first do syntactic checks to verify that we are operating on a valid implicitly typed declaration:

 

// 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;
}

We then perform semantic checks using the semantic model APIs to get semantic type information about the type declaration syntax node and verify it is not an error type or primitive system type:

// 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;
}
You can perform many powerful semantic operations on the syntax node exposed from the SyntaxNodeAnalysisContext using the public semantic model APIs, for reference see https://github.com/dotnet/roslyn/blob/master/src/Compilers/Core/Portable/Compilation/SemanticModel.cs.

If both the syntactic and semantics check succeed, then we report a diagnostic about recommending explicit type instead of var.

主站蜘蛛池模板: 元朗区| 古浪县| 元阳县| 武鸣县| 邯郸县| 新野县| 铁岭县| 丹棱县| 南投县| 兴化市| 湘阴县| 贵州省| 湟源县| 任丘市| 宁海县| 东海县| 葫芦岛市| 师宗县| 乌鲁木齐市| 集安市| 西青区| 新竹县| 肇庆市| 崇阳县| 泰顺县| 韩城市| 兴海县| 大邑县| 大英县| 蓝田县| 江口县| 洛川县| 漯河市| 凤台县| 都兰县| 宁乡县| 车险| 福泉市| 阜南县| 丹江口市| 谢通门县|