c# - 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;
}
但我不知道如何添加具有价值的参数的属性。有人可以帮我吗?
解决方案
[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());
...
推荐阅读
- node.js - SQS 和 SNS 仅在前一个用户拒绝或没有响应的情况下向用户一一发送通知
- vb.net - 是否可以在 SQLite 中选择更多语句?
- macos - React Native App Atom IDE 错误不允许创建配置文件夹
- flutter - 将项目附加/前置到 ListView
- c# - ASP.NET Core 3.0 Web API 路由不起作用
- sql - 获取通过一个属性连接的父级及其子级
- mysql - Sequelize 中的关联抛出错误为
未连接到 - java - 这个程序有什么错误?它没有给出任何输出。为什么?
- javascript - 如何在 Vue.js 中将列表拆分为页面?
- rest - 使用 OpenAPI 到底有什么意义?