一个参数添加到与罗斯林CodeFixProvider的方法 [英] Add a parameter to a method with a Roslyn CodeFixProvider
问题描述
我正在写一个罗斯林代码分析器的,我想,以确定如果异步
方法做的不的拍摄的CancellationToken
,然后提出一个代码修复,增加了它:
I'm writing a Roslyn Code Analyzer that I want to identify if an async
method does not take a CancellationToken
and then suggest a code fix that adds it:
//Before Code Fix:
public async Task Example(){}
//After Code Fix
public async Task Example(CancellationToken token){}
我已经连接好在 DiagnosticAnalyzer
来正确地检查 methodDeclaration.ParameterList.Parameters
,但我找不到罗斯林报告诊断添加API一个 Paramater
到参数列表
在 CodeFixProvider
I've wired up the DiagnosticAnalyzer
to correctly report a Diagnostic by inspecting the methodDeclaration.ParameterList.Parameters
, but I can't find the Roslyn API for adding a Paramater
to the ParameterList
inside a 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
}
我如何正确地更新方法声明和返回更新文件
?
How do I correctly update the Method Declaration and return the updated Document
?
推荐答案
@Nate Barbettini是正确的,语法节点都是不变的,所以我需要创建的 MethodDeclarationSyntax
,然后用文档中的新方法取代旧法的新版本
的 SyntaxTree
:
@Nate Barbettini is correct, syntax nodes are all immutable, so I needed to create a new version of the MethodDeclarationSyntax
, then replace the old method with the new method in the document
'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);
}
这篇关于一个参数添加到与罗斯林CodeFixProvider的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!