コード例 #1
0
        public override async Task RegisterCodeFixesAsync(CodeFixContext context)
        {
            var document = context.Document;
            var cancellationToken = context.CancellationToken;

            var syntaxRoot = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
            var compilationUnit = (CompilationUnitSyntax)syntaxRoot;

#if CODE_STYLE
            var options = document.Project.AnalyzerOptions.GetAnalyzerOptionSet(syntaxRoot.SyntaxTree, cancellationToken);
            var simplifierOptions = CSharpSimplifierOptions.Create(options, fallbackOptions: null);
#else
            var options = await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false);
            var simplifierOptions = await SimplifierOptions.FromDocumentAsync(document, fallbackOptions: context.Options(document.Project.LanguageServices).SimplifierOptions, cancellationToken).ConfigureAwait(false);
#endif
            var codeStyleOption = options.GetOption(CSharpCodeStyleOptions.PreferredUsingDirectivePlacement);

            // Read the preferred placement option and verify if it can be applied to this code file.
            // There are cases where we will not be able to fix the diagnostic and the user will need to resolve
            // it manually.
            var (placement, preferPreservation) = DeterminePlacement(compilationUnit, codeStyleOption);
            if (preferPreservation)
                return;

            foreach (var diagnostic in context.Diagnostics)
            {
                context.RegisterCodeFix(
                    CodeAction.Create(
                        CSharpAnalyzersResources.Move_misplaced_using_directives,
                        token => GetTransformedDocumentAsync(document, compilationUnit, GetAllUsingDirectives(compilationUnit), placement, simplifierOptions, token),
                        nameof(CSharpAnalyzersResources.Move_misplaced_using_directives)),
                    diagnostic);
            }
        }