gpt4 book ai didi

c# - 使用 Roslyn codefix 向方法参数添加属性

转载 作者:太空宇宙 更新时间:2023-11-03 15:15:18 24 4
gpt4 key购买 nike

我正在使用 Roslyn 制作一个分析器,以将 postsharp [NotNull] 属性添加到方法参数。

private async Task<Document> MakeNotNullAsync(Document document, MethodDeclarationSyntax method, CancellationToken cancellationToken, string paramName)
{

var parameters = method.ChildNodes().OfType<ParameterListSyntax>().First();
var param = parameters.ChildNodes().OfType<ParameterSyntax>().First() as SyntaxNode;



NameSyntax name = SyntaxFactory.ParseName("NotNull");
AttributeSyntax attribute = SyntaxFactory.Attribute(name, null);
Collection<AttributeSyntax> list = new Collection<AttributeSyntax>();
list.Add(attribute);
var separatedlist = SyntaxFactory.SeparatedList(list);
var newLiteral = SyntaxFactory.AttributeList(separatedlist);
Collection<SyntaxNode> synlist = new Collection<SyntaxNode>();
synlist.Add(newLiteral);

var root = await document.GetSyntaxRootAsync();
var newRoot = root.InsertNodesBefore(param, synlist);
var newDocument = document.WithSyntaxRoot(newRoot);
return newDocument;

这是我目前所拥有的(并且肯定有一种更简单的方法来做到这一点)但是当它尝试执行 root.InsertNodesBefore() 时我收到“System.InvalidCastException”。有更好的方法吗?

最佳答案

我通常发现使用 ReplaceNode 更容易。在您的情况下,您只需将 param 替换为具有新属性的参数(通过 WithAttributeLists):

var attribute = SyntaxFactory.AttributeList(
SyntaxFactory.SingletonSeparatedList<AttributeSyntax>(
SyntaxFactory.Attribute(SyntaxFactory.IdentifierName("NotNull"), null)));
var newParam = param.WithAttributeLists(param.AttributeLists.Add(attribute));

var root = await document.GetSyntaxRootAsync();
var newRoot = root.ReplaceNode(param, newParam);
var newDocument = document.WithSyntaxRoot(newRoot);
return newDocument;

请注意,这也处理了 param 具有现有属性的情况。

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

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