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

时间:2018-06-15 18:52:56

标签: c# roslyn

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

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

1 个答案:

答案 0 :(得分:1)

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