Reputation: 2343
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?
Upvotes: 2
Views: 1150
Reputation: 2936
[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());
...
Upvotes: 5