Checking a Variable Type For Code Analysis

佐手、 提交于 2019-12-07 06:46:43

问题


What is the correct way to check a variable's type in a Roslyn code analyzer? I am registering for a ObjectCreationExpressionSyntax node and I can get the type, but I am not certain the correct way to check that it is a type I care about.

I found a way to do it by checking the display string, but I am wondering if there is a more correct way to accomplish this. For example, here is code that is trying to check for an ArrayList creation.

private static void SyntaxValidator(SyntaxNodeAnalysisContext context)
{
    var creation = (ObjectCreationExpressionSyntax)context.Node;

    var variableType = creation.Type as IdentifierNameSyntax;

    if (variableType == null)
        return;

    var variableTypeInfo = context.SemanticModel.GetTypeInfo(context.Node);

    if (variableTypeInfo.Type != null && variableTypeInfo.Type.ToDisplayString().Equals("System.Collections.ArrayList"))
    {
        context.ReportDiagnostic(Diagnostic.Create(Rule, creations.GetLocation(), ""));
    }
} 

回答1:


The normal pattern for doing this is to use Compilation.GetTypeByMetadataName(), and then compare that ITypeSymbol with The one you got back from SemanticModel.GetTypeInfo().

Note: Make sure to use .Equals to compare ITypeSymbol instances, as some of them do not guarantee reference identity.

See: http://source.roslyn.io/Roslyn.Diagnostics.Analyzers/R/fee46febeb0be269.html for an example of an analyzer that does this.



来源:https://stackoverflow.com/questions/31358044/checking-a-variable-type-for-code-analysis

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!