Roslyn CodeFixProvider:向方法添加属性

7

我正在为检测方法声明中是否缺少自定义属性的分析器构建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( );
    }
1个回答

19

请记住,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


这个可以用,但是你能给我推荐一些关于这个主题的好资源吗? - AlexanderM

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接