Roslyn从InvocationExpression获取方法声明 [英] Roslyn Get Method Declaration from InvocationExpression

查看:90
本文介绍了Roslyn从InvocationExpression获取方法声明的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在制作roslyn演示,用于根据属性生成编译器警告

I'm making a roslyn demo for generating compiler warnings from attributes

我有一个分析器来分析方法调用,如下所示:

I have an analyzer to analyze Method Invocations which looks like so:

public override void Initialize(AnalysisContext context)
{
    context.RegisterSyntaxNodeAction(AnalyzerInvocation, SyntaxKind.InvocationExpression);
}

private static void AnalyzerInvocation(SyntaxNodeAnalysisContext context)
{
    var invocation = (InvocationExpressionSyntax)context.Node;
}

我正在尝试找出方法声明,我知道我可以使用 SymbolFinder 搜索方法声明

I'm trying to figure out how to get the method declaration, I know I can use the SymbolFinder to search for the method declaration

var model = compilation.GetSemanticModel(tree);

//Looking at the first method symbol
var methodSyntax = tree.GetRoot().DescendantNodes().OfType<MethodDeclarationSyntax>()
   .First(/*TODO: Execute Find for related symbol */);

此选项既昂贵又烦人,并且可能会出现错误,因为如果您的调用方法是来自程序集,那该怎么办.

This options is expensive and annoying, and it leaves open the possiblity for error because what if your invoking method is coming from an assembly.

从InvocationExpressionSyntax获取方法声明的最简单方法是什么?我应该只使用符号查找器吗?如果失败,请使用冲刷导入的程序集,还是有更简便的更好方法?

What is the easiest way to get the method declaration from an InvocationExpressionSyntax? Should I just be using the symbol finder and if it fails use scour the imported assemblies or is there an easier better way?

推荐答案

如果需要声明要调用的方法,则可以按如下所示进行声明.

If you need the declaration of the method that you are calling, you can get that as follows.

第一步,找出要调用的方法:

In the first step, you find out what method it is that is being called:

var methodSymbol = context
    .SemanticModel
    .GetSymbolInfo(invocation, context.CancellationToken)
    .Symbol as IMethodSymbol;

请记住,有多种原因导致methodSymbol可能为null(例如,您调用的是委托,而不是方法),请对此进行测试.

Remember that there are various reasons why the methodSymbol may be null (e.g. you were invoking a delegate, not a method), so test for that.

然后,您可以找到声明语法引用,并采用第一个语法:

Then you can find the declaring syntax references, and take the first one:

var syntaxReference = methodSymbol
    .DeclaringSyntaxReferences
    .FirstOrDefault();

这也可以为null,例如当您从另一个程序集中调用方法时,请对此进行测试.

This can be null as well, e.g. when you were calling a method from another assembly, so test for that.

最后:

var declaration = syntaxReference.GetSyntax(context.CancellationToken);

这为您提供了语法.如果您需要该声明的语义模型,则可以使用

That gives you the syntax. Should you need a semantic model for that declaration, you can get that using

var semanticModel = context.Compilation.GetSemanticModel(declaration.SyntaxTree);

这篇关于Roslyn从InvocationExpression获取方法声明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆