使用Roslyn创建命名空间代码重构

时间:2016-05-31 16:56:33

标签: c# roslyn roslyn-code-analysis

我尝试使用Roslyn创建代码重构扩展。我想要做的是根据我的默认命名空间重构命名空间。当它只是单个单词时,它成功找到并替换了命名空间,但是当我的命名空间看起来像kuku.riku.example并且我将默认命名空间更改为aaa时,结果是kuku.riku.aaa而不是aaa {1}}。我做错了什么?

我的代码:

    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);
    }

1 个答案:

答案 0 :(得分:1)

正如您所看到的,

RenameSymbolAsync只重命名您传入的命名空间部分。支持添加或删除点的命名空间重命名是我们想要构建的,但还没有。