首页 文章

使用Roslyn CodeFixProvider向方法添加参数

提问于
浏览
4

我正在写一个Roslyn Code Analyzer,我想确定 async 方法是否不采用 CancellationToken 然后建议添加它的代码修复:

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

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

我已经通过检查 methodDeclaration.ParameterList.Parameters 来连接 DiagnosticAnalyzer 以正确报告诊断,但我找不到用于在 CodeFixProvider 内向 ParameterList 添加 Paramater 的Roslyn API .

这是我到目前为止所得到的:

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

1 回答

  • 2

    @Nate Barbettini是正确的,语法节点都是不可变的,所以我需要创建一个新版本的 MethodDeclarationSyntax ,然后用 document 的_267484中的新方法替换旧方法:

    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);
        }
    

相关问题