当你有一个调用节点时,你可以看到它的表达式是否是成员访问。如果调用是针对语句“DoThis()”,那么没有成员访问,但如果调用是针对“x.DoThis()”,那么是成员访问,因为针对参考“x”。
一旦您确认是成员访问,您可能会获得目标引用的表达式 - 这是目标引用的表达式 - 这是其成员被访问的引用。这个表达式可能是一个简单的名称标识符(例如“command”)或者它可能是另一个成员访问(例如“x.command”)或者它可能是另一个调用(例如“GetCommand()”),或者它可能是这些的组合。
要使用代码说明 -
private static void AnalyseInvocation(SyntaxNodeAnalysisContext context)
{
var invocation = (InvocationExpressionSyntax)context.Node;
var memberAccess = invocation.Expression as MemberAccessExpressionSyntax;
if ((memberAccess == null) || (memberAccess.Name.Identifier.ValueText != "ExecuteReader"))
return;
if (memberAccess.Expression is IdentifierNameSyntax)
{
// The target is a simple identifier, the code being analysed is of the form
// "command.ExecuteReader()" and memberAccess.Expression is the "command"
// node
}
else if (memberAccess.Expression is InvocationExpressionSyntax)
{
// The target is another invocation, the code being analysed is of the form
// "GetCommand().ExecuteReader()" and memberAccess.Expression is the
// "GetCommand()" node
}
else if (memberAccess.Expression is MemberAccessExpressionSyntax)
{
// The target is a member access, the code being analysed is of the form
// "x.Command.ExecuteReader()" and memberAccess.Expression is the "x.Command"
// node
}
}
在那些只是链接调用/简单构件访问结束。如果你得到最内层的调用(或'SimpleMemberAccessExpression'),你有你想要的。看看直接的父母,而不是所有的祖先。 –
是否有更好的方式,而不是硬编码呢?例如,获取方法调用的符号,然后从符号中确定调用该方法的对象的实例。例如:'ClassA varA = new ClassA(); varA.methodA()'得到'methodA()'的符号,并发现'varA'调用它。 –
“硬编码”是什么意思?如果你想要这个调用,你必须编写获取调用的代码。 –