AbstractMakeClassAbstractCodeFixProvider.cs 2.4 KB
Newer Older
E
Evangelink 已提交
1 2 3
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
A
Amaury Levé 已提交
4

A
Amaury Levé 已提交
5 6
#nullable enable

A
Amaury Levé 已提交
7 8 9 10 11 12 13 14 15 16 17 18 19 20
using System;
using System.Collections.Immutable;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.Shared.Extensions;

namespace Microsoft.CodeAnalysis.MakeClassAbstract
{
    internal abstract class AbstractMakeClassAbstractCodeFixProvider<TClassDeclarationSyntax> : SyntaxEditorBasedCodeFixProvider
        where TClassDeclarationSyntax : SyntaxNode
    {
A
Amaury Levé 已提交
21 22
        protected abstract bool IsValidRefactoringContext(SyntaxNode? node, out TClassDeclarationSyntax? classDeclaration);

A
Amaury Levé 已提交
23 24 25 26
        internal sealed override CodeFixCategory CodeFixCategory => CodeFixCategory.Compile;

        public sealed override Task RegisterCodeFixesAsync(CodeFixContext context)
        {
A
Amaury Levé 已提交
27
            if (IsValidRefactoringContext(context.Diagnostics[0].Location?.FindNode(context.CancellationToken), out _))
A
Amaury Levé 已提交
28 29 30 31 32 33 34 35 36 37 38 39 40 41
            {
                context.RegisterCodeFix(
                    new MyCodeAction(c => FixAsync(context.Document, context.Diagnostics[0], c)),
                    context.Diagnostics);
            }

            return Task.CompletedTask;
        }

        protected sealed override Task FixAllAsync(Document document, ImmutableArray<Diagnostic> diagnostics, SyntaxEditor editor,
            CancellationToken cancellationToken)
        {
            for (var i = 0; i < diagnostics.Length; i++)
            {
A
Amaury Levé 已提交
42
                if (IsValidRefactoringContext(diagnostics[i].Location?.FindNode(cancellationToken), out var classDeclaration))
A
Amaury Levé 已提交
43
                {
A
Amaury Levé 已提交
44
                    editor.ReplaceNode(classDeclaration,
A
Amaury Levé 已提交
45 46 47 48 49 50 51 52 53 54
                        (currentClassDeclaration, generator) => generator.WithModifiers(currentClassDeclaration, DeclarationModifiers.Abstract));
                }
            }

            return Task.CompletedTask;
        }

        private class MyCodeAction : CodeAction.DocumentChangeAction
        {
            public MyCodeAction(Func<CancellationToken, Task<Document>> createChangedDocument)
A
Amaury Levé 已提交
55
                : base(FeaturesResources.Make_class_abstract, createChangedDocument, FeaturesResources.Make_class_abstract)
A
Amaury Levé 已提交
56 57 58 59 60
            {
            }
        }
    }
}