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

Roslyn CodeFixProvider add attribute with argument having value

我正在为检测 class 声明中是否缺少 MessagePackObject 属性的分析器创建一个 CodeFixProvider。此外,我的属性需要有一个参数 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());
...