简体   繁体   English

使用Roslyn CodeFixProvider向方法添加参数

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

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: 我正在编写一个Roslyn代码分析器 ,我想识别async方法是否采用CancellationToken然后建议添加它的代码修复:

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

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

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 . 我已经通过检查methodDeclaration.ParameterList.Parameters来连接DiagnosticAnalyzer来正确报告Diagnostic,但是我找不到Roslyn API来将Paramater添加到CodeFixProviderParameterList

This is what I've got so far: 这是我到目前为止所得到的:

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 ? 如何正确更新方法声明并返回更新的Document

@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 : @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