[英]c# Roslyn get IParameterSymbol from ArgumentSyntax
I have an ArgumentSyntax
in some invocation expression, how can I get corresponding IParameterSymbol
in the IMethodSymbol
of the invocation?我在某个调用表达式中有一个
ArgumentSyntax
,如何在调用的IParameterSymbol
中获取对应的IMethodSymbol
?
Since I have seen ArgumentSyntax.NameColonSyntax
, which means the argument might have some name, I cannot use IParameterSymbol.Ordinal
to match them by their index in their containing list.由于我已经看到
ArgumentSyntax.NameColonSyntax
,这意味着参数可能有一些名称,所以我不能使用IParameterSymbol.Ordinal
通过它们在包含列表中的索引来匹配它们。
Let's take a look at the following snippet:让我们看一下以下代码段:
public class Foo {
public void Bar(int first, int second) {
Add(first, second);
Add(y: second, x: first);
}
public int Add(int x, int y) => x + y;
}
In this case, the Add
method is called twice, first with ordinal parameters and a second time with named parameters.在这种情况下,
Add
方法被调用两次,第一次使用序数参数,第二次使用命名参数。
If we try to get the parameters by using the index we will not get the right result for the second call.如果我们尝试使用索引来获取参数,我们将不会在第二次调用中得到正确的结果。
One way to solve this (if you know the name beforehand) is to try to get the argument by name and as a backup to use the index:解决此问题的一种方法(如果您事先知道名称)是尝试按名称获取参数并作为使用索引的备份:
private static ArgumentSyntax GetArgument(InvocationExpressionSyntax invocation, string name, int ordinal) =>
GetArgument(invocation, name) ?? GetArgument(invocation, ordinal);
private static ArgumentSyntax GetArgument(InvocationExpressionSyntax invocation, string name) =>
invocation.ArgumentList.Arguments
.FirstOrDefault(argumentSyntax => argumentSyntax.NameColon?.Name.Identifier.Text == name);
private static ArgumentSyntax GetArgument(InvocationExpressionSyntax invocation, int ordinal) =>
invocation.ArgumentList.Arguments[ordinal];
If the parameter names are not know beforehand you can get the method symbol:如果事先不知道参数名称,您可以获取方法符号:
var methodSymbol = (IMethodSymbol) semanticModel.GetSymbolInfo(invocations[0].Expression).Symbol;
look at the declaring syntax references:查看声明语法参考:
var methodDeclarationSyntax = methodSymbol.DeclaringSyntaxReferences.First().GetSyntax() as MethodDeclarationSyntax;
and get the parameter names from the declaration:并从声明中获取参数名称:
methodDeclarationSyntax.ParameterList.Parameters[0].Identifier.Text
but this will work only if method is declared in the same solution.但这只有在同一解决方案中声明方法时才有效。
I've been trying to figure out the same process myself and after fumbling a bit I found a path forward for this.我一直在尝试自己找出相同的过程,在摸索了一下之后,我找到了一条前进的道路。 It requires access to the
SemanticModel
.它需要访问
SemanticModel
。 In my case it comes from the context of a Roslyn analyzer.就我而言,它来自 Roslyn 分析器的上下文。
SemanticModel.GetOperation(argumentSyntaxNode)
should return an IArgumentOperation
which has a property IParameterSymbol Parameter
SemanticModel.GetOperation(argumentSyntaxNode)
应该返回一个IArgumentOperation
,它有一个属性IParameterSymbol Parameter
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.