簡體   English   中英

無論如何,在羅斯林中基於InvocationExpressionSyntax獲得MethodDeclarationSyntax?

[英]Is there anyway to get MethodDeclarationSyntax based on InvocationExpressionSyntax in 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 ?????
    }
 }

我懷疑您只是想獲取語義模型,向其詢問符號並獲取屬性:

// 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

我不知道獲取語義模型的成本是多少-可能會有更多性能更好的選擇,但是我希望這至少能起作用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM