gpt4 book ai didi

c# - Roslyn CodeFixProvider 向方法添加属性

转载 作者:太空狗 更新时间:2023-10-30 00:04:37 26 4
gpt4 key购买 nike

我正在为检测方法声明中是否缺少自定义属性的分析器构建 CodeFixProvider。基本上应该添加到方法中的自定义属性看起来像

    [CustomAttribute(param1: false, param2: new int[]{1,2,3})]

这是我到目前为止所得到的:

    public sealed override async Task RegisterCodeFixesAsync( CodeFixContext context ) {
var root = await context.Document.GetSyntaxRootAsync( context.CancellationToken ).ConfigureAwait( false );

var diagnostic = context.Diagnostics.First();
var diagnosticSpan = diagnostic.Location.SourceSpan;
var declaration = root.FindToken( diagnosticSpan.Start ).Parent.AncestorsAndSelf( ).OfType<MethodDeclarationSyntax>( ).First( );

context.RegisterCodeFix(
CodeAction.Create(
title: title,
createChangedSolution: c => this.AddCustomAttribute(context.Document, declaration, c),
equivalenceKey: title),
diagnostic);
}

private async Task<Solution> AddCustomAttribute( Document document, MethodDeclarationSyntax methodDeclaration, CancellationToken cancellationToken ) {
// I suspect I need to do something like methodDeclaration.AddAttributeLists(new AttributeListSyntax[] {
// but not sure how to use it exactly

throw new NotImplementedException( );
}

最佳答案

请记住,roslyn 语法树是不可变的。你需要这样的东西:

private async Task<Solution> AddCustomAttribute(Document document, MethodDeclarationSyntax methodDeclaration, CancellationToken cancellationToken)
{
var root = await document.GetSyntaxRootAsync(cancellationToken);
var attributes = methodDeclaration.AttributeLists.Add(
SyntaxFactory.AttributeList(SyntaxFactory.SingletonSeparatedList<AttributeSyntax>(
SyntaxFactory.Attribute(SyntaxFactory.IdentifierName("CustomAttribute"))
// .WithArgumentList(...)
)).NormalizeWhitespace());

return document.WithSyntaxRoot(
root.ReplaceNode(
methodDeclaration,
methodDeclaration.WithAttributeLists(attributes)
)).Project.Solution;
}

要获取属性构造函数 .WithArgumentList() 的完整 SyntaxFactory 代码,请将其放入 Roslyn Quoter 中.

关于c# - Roslyn CodeFixProvider 向方法添加属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37594739/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com