gpt4 book ai didi

c# - Roslyn CodeFixProvider 添加具有值的参数的属性

转载 作者:行者123 更新时间:2023-12-02 20:22:51 26 4
gpt4 key购买 nike

我正在为分析器创建一个 CodeFixProvider,用于检测类声明中是否缺少 MessagePackObject 属性。此外,我的属性需要有一个参数 keyAsPropertyName ,其值为 true

[MessagePackObject(keyAsPropertyName:true)]

我已经添加了不带参数的属性,就像这样(我的解决方案方法)

private async Task<Solution> AddAttributeAsync(Document document, ClassDeclarationSyntax classDecl, CancellationToken cancellationToken)
{
var root = await document.GetSyntaxRootAsync(cancellationToken);
var attributes = classDecl.AttributeLists.Add(
SyntaxFactory.AttributeList(SyntaxFactory.SingletonSeparatedList(
SyntaxFactory.Attribute(SyntaxFactory.IdentifierName("MessagePackObject"))
// .WithArgumentList(SyntaxFactory.AttributeArgumentList(SyntaxFactory.SingletonSeparatedList(SyntaxFactory.AttributeArgument(SyntaxFactory.("keyAsPropertyName")))))))
// .WithArgumentList(...)
)).NormalizeWhitespace());

return document.WithSyntaxRoot(
root.ReplaceNode(
classDecl,
classDecl.WithAttributeLists(attributes)
)).Project.Solution;
}

但我不知道如何添加具有值的参数的属性。有人可以帮我吗?

最佳答案

[MessagePackObject(keyAsPropertyName:true)] 是一个 AttributeArgumentSyntax ,它具有 NameColons 但没有 NameEquals,因此您只需创建它,不传递任何内容作为 NameEquals 和传递正确的初始表达式,如下所示:

...
var attributeArgument = SyntaxFactory.AttributeArgument(
null, SyntaxFactory.NameColon("keyAsPropertyName"), SyntaxFactory.LiteralExpression(SyntaxKind.TrueLiteralExpression));

var attributes = classDecl.AttributeLists.Add(
SyntaxFactory.AttributeList(SyntaxFactory.SingletonSeparatedList(
SyntaxFactory.Attribute(SyntaxFactory.IdentifierName("MessagePackObject"))
.WithArgumentList(SyntaxFactory.AttributeArgumentList(SyntaxFactory.SingletonSeparatedList(attributeArgument)))
)).NormalizeWhitespace());
...

关于c# - Roslyn CodeFixProvider 添加具有值的参数的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50881267/

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