[英]Add a parameter to a method with a 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<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
?
@Nate Barbettini是正確的,語法節點都是不可變的,所以我需要創建一個新版本的MethodDeclarationSyntax
,然后用document
的SyntaxTree
的new方法替換舊方法:
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);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.