编程语言
首页 > 编程语言> > 首页> C#>查找包含给定的SyntaxNode的MethodDeclarationSyntax

首页> C#>查找包含给定的SyntaxNode的MethodDeclarationSyntax

作者:互联网

我有以下源代码:

public void MethodAssignment_WithIndexQuery_1(Customer from1, Customer to1, decimal amount) 
{
     var customers = _customerRepository.GetWhere(to1.Age);
     Customer indexCustomer1 = customers[(from1.Age + to1.Age)* to1.Age];
}

我给定了SyntaxNode:node = from1.index表达式中表达式的年龄.

这样做将产生空值:

MethodDeclarationSyntax callingMethod = node
                .GetLocation()
                .SourceTree
                .GetRoot()
                .FindToken(location.SourceSpan.Start)
                .Parent
                .AncestorsAndSelf()
                .OfType<MethodDeclarationSyntax>()
                .FirstOrDefault();

执行node.Parent.Parent返回BinaryExpressionSyntax AddExpression from1.Age * to2.Age to1.Age * to2.Age并执行Parent产生null.

如何找到包围给定语法节点的MethodDeclaration?

解决方法:

SyntaxWalker允许您查找特定的节点.这是一个如何获取所有AddExpression节点的示例:

public class MethodDeclarationSyntaxWalker : CSharpSyntaxWalker
{
    private readonly IList<MethodDeclarationSyntax> _matches;

    public MethodDeclarationSyntaxWalker( IList<MethodDeclarationSyntax> matches )
    {
        _matches = matches;
    }

    public override void VisitBinaryExpression( BinaryExpressionSyntax node )
    {
        if ( node.Kind() == SyntaxKind.AddExpression )
            _matches.Add( node.FirstAncestorOrSelf<MethodDeclarationSyntax>() );

        base.VisitBinaryExpression( node );
    }
}

如果在声明语法的Accept函数中传递此值,它将收集与给定节点匹配的内容.例如:

var classDeclaration = ( ClassDeclarationSyntax )analysisContext.Node;
var matches = new List<MethodDeclarationSyntax>();
classDeclaration.Accept( new MethodDeclarationSyntaxWalker( matches ) );

标签:roslyn,roslyn-code-analysis,c
来源: https://codeday.me/bug/20191109/2010693.html