使用Roslyn CodeFixProvider向方法添加参数
我正在编写一个Roslyn代码分析器 ,我想识别async
方法是否不采用CancellationToken
然后建议添加它的代码修复:
//Before Code Fix: public async Task Example(){} //After Code Fix public async Task Example(CancellationToken token){}
我已经通过检查methodDeclaration.ParameterList.Parameters
来连接DiagnosticAnalyzer
来正确报告Diagnostic,但是我找不到Roslyn API来将Paramater
添加到CodeFixProvider
的ParameterList
。
这是我到目前为止所得到的:
private async Task 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
?
@Nate Barbettini是正确的,语法节点都是不可变的,所以我需要创建一个新版本的MethodDeclarationSyntax
,然后用document
的SyntaxTree
的new方法替换旧方法:
private async Task 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); }