簡體   English   中英

Roslyn CodeFixProvider為該方法添加屬性

[英]Roslyn CodeFixProvider add attribute to the method

我正在為分析器構建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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM