6

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

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

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

我已DiagnosticAnalyzer通过检查 连接正确报告诊断methodDeclaration.ParameterList.Parameters,但我找不到用于将 a 添加ParamaterParameterList内部的 Roslyn API 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         
}

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

4

1 回答 1

7

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

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);
    }
于 2016-04-29T23:17:38.840 回答