无论如何在Roslyn中基于InvocationExpressionSyntax获取MethodDeclarationSyntax?

时间:2017-05-14 17:18:51

标签: c# roslyn

我想用roslyn编写代码重构,所以我编写了一个像

这样的代码
class Program
{
    [Obsolete()]
    public static void A() { }

    static void Main(string[] args)
    {
        A(); // I moved the mouse here and captured as InvocationExpressionSyntax 
        Console.WriteLine("Hello World!");
    }
}

我选择A()作为InvocationExpressionSyntax,所以我想知道我可以获得MethodDeclarationSyntax或更好的所选方法的属性。

装置

public static void A() { }

[Obsolete()]

有可能吗?

我想找到重构目的的方法的所有属性。

编辑

public sealed override async Task ComputeRefactoringsAsync(CodeRefactoringContext context)
{
    // TODO: Replace the following code with your own analysis, generating a CodeAction for each refactoring to offer

    var root = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false);

    // Find the node at the selection.
    var node = root.FindNode(context.Span);

    // Only offer a refactoring if the selected node is a type declaration node.
    var typeDecl = node.Parent as InvocationExpressionSyntax;
    if (typeDecl == null)
    {
        return;
    }

    // For any type declaration node, create a code action to reverse the identifier text.
    var action = CodeAction.Create("Reverse type name", c => ReverseTypeNameAsync(context.Document, typeDecl, c));

    // Register this code action.
    context.RegisterRefactoring(action);
}

编辑2

ClassLibrary1:

[AttributeUsage(AttributeTargets.Method, AllowMultiple = true, Inherited = false)]
    public class CustomAttribute : Attribute
    {}

ClassLibrary2

public static class Class1
{
    [CustomAttribute] // Comes from ClassLibrary1
    public static string SayHelloTo(string name)
    {
        return $"Hello {name}";
    }

代码重构项目:

class Program
{
    [Obsolete()]
    public static void A() { }

    static void Main(string[] args)
    {
        A(); // I moved the mouse here and captured as InvocationExpressionSyntax 
        var t = ClassLibrary2.Class1.SayHelloTo("Test");  // ????? Symbol is NULL ?????
    }
 }

1 个答案:

答案 0 :(得分:0)

我怀疑你只是想得到语义模型,问它符号,并获得属性:

// After you've made sure that you've got an InvocationExpressionSyntax
var model = await context.Document
    .GetSemanticModelAsync(context.CancellationToken)
    .ConfigureAwait(false);
var symbol = model.GetSymbolInfo(invocation);
var attributes = symbol.Symbol?.GetAttributes();
// Examine attributes; it will be null if the symbol wasn't resolved

我不知道获得语义模型的成本有多高 - 可能有更多高性能的替代品,但我希望这至少可以起作用。

相关问题