使用Roslyn CodeFixProvider向方法添加参数

时间:2016-04-29 22:10:36

标签: c# code-analysis roslyn roslyn-code-analysis

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

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

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

我已通过检查DiagnosticAnalyzermethodDeclaration.ParameterList.Parameters连接到正确报告诊断,但我找不到用于向{{1}添加Paramater的Roslyn API在ParameterList内。

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

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 }

1 个答案:

答案 0 :(得分:3)

@Nate Barbettini是正确的,语法节点都是不可变的,所以我需要创建MethodDeclarationSyntax的新版本,然后用document&#39中的新方法替换旧方法; 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);
    }