gpt4 book ai didi

c# - 使用 Roslyn CodeFixProvider 向方法添加参数

转载 作者:太空狗 更新时间:2023-10-30 01:32:31 26 4
gpt4 key购买 nike

我正在写一个 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 以正确报告诊断,但我找不到用于添加诊断的 Roslyn API ParamaterCodeFixProvider 内的 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
}

如何正确更新方法声明并返回更新后的文档

最佳答案

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

关于c# - 使用 Roslyn CodeFixProvider 向方法添加参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36948218/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com