我正在为分析器创建一个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 回答
[MessagePackObject(keyAsPropertyName:true)]
是AttributeArgumentSyntax
,它有NameColons并且没有NameEquals,所以你只需创建它就像NameEquals一样传递并传递正确的初始表达式,如下所示: