一个参数添加到与罗斯林CodeFixProvider的方法 [英] Add a parameter to a method with a Roslyn CodeFixProvider

查看:226
本文介绍了一个参数添加到与罗斯林CodeFixProvider的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在写一个罗斯林代码分析器的,我想,以确定如果异步方法做的的拍摄的CancellationToken ,然后提出一个代码修复,增加了它:

I'm writing a Roslyn Code Analyzer that I want to identify if an async method does not take a CancellationToken and then suggest a code fix that adds it:

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

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

我已经连接好在 DiagnosticAnalyzer 来正确地检查 methodDeclaration.ParameterList.Parameters ,但我找不到罗斯林报告诊断添加API一个 Paramater 参数列表 CodeFixProvider

I've wired up the DiagnosticAnalyzer to correctly report a Diagnostic by inspecting the methodDeclaration.ParameterList.Parameters, but I can't find the Roslyn API for adding a Paramater to the ParameterList inside a CodeFixProvider.

这是我到目前为止有:

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         
}

我如何正确地更新方法声明和返回更新文件

How do I correctly update the Method Declaration and return the updated Document?

推荐答案

@Nate Barbettini是正确的,语法节点都是不变的,所以我需要创建的 MethodDeclarationSyntax ,然后用文档中的新方法取代旧法的新版本 SyntaxTree

@Nate Barbettini is correct, syntax nodes are all immutable, so I needed to create a new version of the MethodDeclarationSyntax, then replace the old method with the new method in the document's SyntaxTree:

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

这篇关于一个参数添加到与罗斯林CodeFixProvider的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆