簡體   English   中英

使用Roslyn CodeFixProvider向方法添加參數

[英]Add a parameter to a method with a Roslyn CodeFixProvider

我正在編寫一個Roslyn代碼分析器 ,我想識別async方法是否采用CancellationToken然后建議添加它的代碼修復:

 //Before Code Fix:
 public async Task Example(){}

 //After Code Fix
 public async Task Example(CancellationToken token){}

我已經通過檢查methodDeclaration.ParameterList.Parameters來連接DiagnosticAnalyzer來正確報告Diagnostic,但是我找不到Roslyn API來將Paramater添加到CodeFixProviderParameterList

這是我到目前為止所得到的:

private async Task<Document> HaveMethodTakeACancellationTokenParameter(
        Document document, SyntaxNode syntaxNode, CancellationToken cancellationToken)
{
    var method = syntaxNode as MethodDeclarationSyntax;

    // what goes here?
    // what I want to do is: 
    // method.ParameterList.Parameters.Add(
          new ParameterSyntax(typeof(CancellationToken));

    //somehow return the Document from method         
}

如何正確更新方法聲明並返回更新的Document

@Nate Barbettini是正確的,語法節點都是不可變的,所以我需要創建一個新版本的MethodDeclarationSyntax ,然后用documentSyntaxTree的new方法替換舊方法:

private async Task<Document> HaveMethodTakeACancellationTokenParameter(
        Document document, SyntaxNode syntaxNode, CancellationToken cancellationToken)
    {
        var method = syntaxNode as MethodDeclarationSyntax;

        var updatedMethod = method.AddParameterListParameters(
            SyntaxFactory.Parameter(
                SyntaxFactory.Identifier("cancellationToken"))
                .WithType(SyntaxFactory.ParseTypeName(typeof (CancellationToken).FullName)));

        var syntaxTree = await document.GetSyntaxTreeAsync(cancellationToken);

        var updatedSyntaxTree = 
            syntaxTree.GetRoot().ReplaceNode(method, updatedMethod);

        return document.WithSyntaxRoot(updatedSyntaxTree);
    }

暫無
暫無

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

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