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

Ale*_*kov 2 c# roslyn

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

[MessagePackObject(keyAsPropertyName:true)]
Run Code Online (Sandbox Code Playgroud)

我已经完成了像这样添加没有参数的属性(我的解决方法)

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;
}
Run Code Online (Sandbox Code Playgroud)

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

Geo*_*ria 5

[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());
...
Run Code Online (Sandbox Code Playgroud)