简体   繁体   中英

Create Namespace Code Refactoring using Roslyn

I'm trying to create code refactoring extension using Roslyn. What I want to do is refactor namespaces according to my default namespace. It succeed to find and replace the namespace when it is single word only but when my namespaces looks like that kuku.riku.example and I change my default namespace to aaa the result is kuku.riku.aaa instead of just aaa . What am I doing wrong?

My code:

    public sealed override async Task ComputeRefactoringsAsync(CodeRefactoringContext context)
    {
        SyntaxNode node = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false);

        NamespaceDeclarationSyntax namespaceDec = (NamespaceDeclarationSyntax)node.ChildNodes()
                                                                                  .FirstOrDefault(syntaxNode => syntaxNode as NamespaceDeclarationSyntax != null);

        string defaultNamespace = GetDefaultNamespace(context.Document);

        if (defaultNamespace != namespaceDec.Name.ToString())
        {
            var action = CodeAction.Create("Adjust Namespaces", c => AdjustNamespacesAsync(context.Document, namespaceDec, defaultNamespace, context.CancellationToken));

            // Register this code action.
            context.RegisterRefactoring(action);
        }

    }

    private static async Task<Solution> AdjustNamespacesAsync(Document document, NamespaceDeclarationSyntax declerationSyntax, string newName, CancellationToken cancelationToken)
    {
        SemanticModel semanticModel = await document.GetSemanticModelAsync(cancelationToken);
        var fist = declerationSyntax.Span;
        INamespaceSymbol symbol = semanticModel.GetDeclaredSymbol(declerationSyntax, cancelationToken);


        Solution origionalSolution = document.Project.Solution;
        OptionSet workspaceOptions = document.Project.Solution.Workspace.Options;



        return await Renamer.RenameSymbolAsync(origionalSolution, symbol, newName, workspaceOptions, cancelationToken);
    }

RenameSymbolAsync renames just the part of the namespace that you're passing in, as you're seeing. Supporting namespace renames that add or remove dots is something we've wanted to build, but just haven't yet.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM