我正在编写一个Roslyn Code Analyzer,我想确定async
方法是否不获取CancellationToken
,然后建议添加的代码修复它:
//Before Code Fix:
public async Task Example(){}
//After Code Fix
public async Task Example(CancellationToken token){}
我已通过检查DiagnosticAnalyzer
将methodDeclaration.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
}
?
答案 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);
}