我正在尝试使用 Roslyn 创建代码重构扩展。我想要做的是根据我的默认命名空间重构命名空间。kuku.riku.example
当命名空间只有单个单词但我的命名空间看起来像这样并且我将默认命名空间更改aaa
为结果时,它会成功找到并替换命名空间kuku.riku.aaa
而不是aaa
. 我究竟做错了什么?
我的代码:
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);
}