简体   繁体   中英

Roslyn CodeFixProvider add attribute with argument having value

I'm creating a CodeFixProvider for the analyzer that is detecting if MessagePackObject attribute is missing from the class declaration. Beside, My attribute need to have one argument keyAsPropertyName with value true

[MessagePackObject(keyAsPropertyName:true)]

I have done adding attribute without arguments like so(my solution method)

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;
}

But I don't know how add attribute with argument having value. Can somebody help me please?

[MessagePackObject(keyAsPropertyName:true)] is a AttributeArgumentSyntax that has NameColons and doesn't have NameEquals, so you just need to create it passing nothing as NameEquals and passing the correct initial expression like this:

...
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());
...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM