我有以下源代码:
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.Age 。
这样做会产生null:
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
?
答案 0 :(得分:3)
final list = List.filled(5, 0);
print(list); //-> [0, 0, 0, 0, 0]
允许您查找特定节点。以下是获取所有SyntaxWalker
节点的示例:
AddExpression
如果你在declarationsyntax的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
答案 1 :(得分:0)
您可以通过Ancestors()
检索节点的封闭方法:
MethodDeclarationSyntax callingMethod = node
.Ancestors()
.OfType<MethodDeclarationSyntax>()
.FirstOrDefault();