Obtaining name of a method parameter from the corresponding argument in a method invocation in Roslyn

无人久伴 提交于 2019-12-10 21:21:34

问题


I was wondering if there was some existing logic to obtain the name (or any other relevant information) about the definition of a parameter in its containing method/constructor signature by looking at an invocation of that particular method/constructor. Basically, I just want to be able to get a default name for a variable that will be passed as an argument to the invocation. So, if a method if defined as such:

public void Foo(object firstParam, object secondParam, object thirdParam)

I would want to be able to say that the second argument of the following invocation

object bar = null;
this.Foo(null, bar, null)

is expected to have the name "secondParam". Basically, I just want to relate an argument to the original parameter whose "spot" it occupies in the invocation.

I am asking if any util methods that I am not aware of already exist within Roslyn, as there are some more complex scenarios to handle, such as named or optionnal arguments. The solution I've come up with in the meantime should covers some cases, but probably not all (especially params, which should require some more specialized logic to handle). Here's what I have so far:

    private IEnumerable<IdentifierNameSyntax> GetParameterNamesFromArgumentList(ArgumentListSyntax argumentList, SyntaxNodeAnalysisContext context)
    {
        var arguments = argumentList.Arguments;
        var parameters = argumentList.Parent.GetSymbolOrDeclaredAs<IMethodSymbol>(context)?.Parameters;

        if (parameters != null)
        {
            var index = 0;
            foreach (var parameter in parameters)
            {
                var argument = index < arguments.Count ? arguments[index] : null;

                if (argument != null && argument.NameColon == null)
                {
                    yield return SyntaxFactory.IdentifierName(parameter.Name);
                }
                else if (argument != null)
                {
                    yield return argument.NameColon.Name;
                }

                index++;
            }
        }
    }

I could be using DeclaringSyntaxReferenceson the method symbol, but I think that just having the names from the IParameterSymbol suited my needs well enough. Again, if this kind of logic is already implemented anywhere else, I'd rather use it. If not, well, feel free to tell me what you think of the problem.


回答1:


Sadly I don't think there is a good public way to do this. See Roslyn's internal DetermineParameter helper for something that might help.



来源:https://stackoverflow.com/questions/30242345/obtaining-name-of-a-method-parameter-from-the-corresponding-argument-in-a-method

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