编程语言
首页 > 编程语言> > c# – 使用Roslyn CodeFixProvider向方法添加参数

c# – 使用Roslyn CodeFixProvider向方法添加参数

作者:互联网

我正在编写一个Roslyn Code Analyzer,我想识别异步方法是否不采用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添加到CodeFixProvider中的ParameterList.

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

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         
}

如何正确更新方法声明并返回更新的文档?

解决方法:

@Nate Barbettini是正确的,语法节点都是不可变的,所以我需要创建一个新版本的MethodDeclarationSyntax,然后用文档的SyntaxTree中的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);
    }

标签:c,code-analysis,roslyn,roslyn-code-analysis
来源: https://codeday.me/bug/20190702/1354557.html