【问题标题】:Add a parameter to a method with a Roslyn CodeFixProvider使用 Roslyn CodeFixProvider 向方法添加参数
【发布时间】:2016-04-29 22:10:36
【问题描述】:

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

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

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

我已通过检查methodDeclaration.ParameterList.Parameters 连接DiagnosticAnalyzer 以正确报告诊断,但我找不到用于在CodeFixProvider 内将Paramater 添加到ParameterList 的Roslyn API。

这是我目前得到的:

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

【问题讨论】:

  • 我相信你必须替换整个ParameterList,而不是添加一个新参数。我已经有一段时间没有写分析器了!
  • ParamaterList 没有设置器 :(。我需要从头开始创建一个新的 MethodDeclaration 吗?
  • 我想是的。如果你想把这段代码扔到 github 上,我很乐意尝试一下。

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


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-06
    相关资源
    最近更新 更多