首页 > 解决方案 > Roslyn CodeFixProvider 添加具有参数值的属性

问题描述

我正在为检测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;
}

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

标签: c#roslyn

解决方案


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

推荐阅读