【问题标题】:Roslyn: Add using statements to Syntax treeRoslyn:将 using 语句添加到语法树
【发布时间】:2020-08-28 03:31:05
【问题描述】:

我已经成功创建了一个代码修复程序,如果通用工厂类中缺少工厂方法,它会生成工厂方法。 当我查看已修复的文件时,由于缺少 using 语句,我收到了许多错误。

我已经能够创建一个我想添加到重构文件中的 UsingDirectives 列表。如何将这些使用添加到文件中?

    private async Task<Solution> FixUpFactory(Document document, TypeDeclarationSyntax typeDecl, CancellationToken cancellationToken)
        {
...
var factorySyntaxTree = factoryClass.DeclaringSyntaxReferences.Select(x => x.SyntaxTree);
var factoryDocument = document.Project.GetDocument(factorySyntaxTree.FirstOrDefault());
var usingDirectives = FindUsingDirectives(factorySyntaxTree.FirstOrDefault());
var methodUsingDirectives = FindMethodUsingDirectives(createMethods);
var usingDirectivesToAdd = new SyntaxList<UsingDirectiveSyntax>(methodUsingDirectives.Except(usingDirectives).Distinct());
...
//replace 
var factoryTree = await factoryDocument.GetSyntaxTreeAsync();
var compUnitSyntax = factoryTree.GetCompilationUnitRoot();
var newCompUnitSyntax = compUnitSyntax.WithUsings(usingDirectivesToAdd);

var documentRoot = await factoryDocument.GetSyntaxRootAsync().ConfigureAwait(false);
//newRoot comes out the same as the documentRoot
var newRoot= documentRoot.ReplaceNode(compUnitSyntax, newCompUnitSyntax);
var factorySolution = document.Project.Solution.WithDocumentSyntaxRoot(factoryDocument.Id, newRoot);
}

那么,如何让 newRoot 反映我想添加的新 using 指令?

【问题讨论】:

    标签: c# roslyn roslyn-code-analysis


    【解决方案1】:

    我最终打破了我的代码。 这两种方法都有效:

    private SyntaxTree UpdateUsingDirectives(SyntaxTree originalTree, UsingDirectiveSyntax[] newUsings)
    {
        var rootNode = originalTree.GetRoot() as CompilationUnitSyntax;
        rootNode = rootNode.AddUsings(newUsings).NormalizeWhitespace();
        return rootNode.SyntaxTree;
    }
    
    private SyntaxTree UpdateUsingDirectives(SyntaxTree originalTree, SyntaxList<UsingDirectiveSyntax> newUsings)
    {
        var rootNode = originalTree.GetRoot() as CompilationUnitSyntax;
        rootNode = rootNode.WithUsings(newUsings).NormalizeWhitespace();
        return rootNode.SyntaxTree;
    }
    

    注意第二个替换了 usings。

    之后,您可以执行以下操作:

    var newFactory = UpdateUsingDirectives(factoryTree, newUsings);
    var newFactoryRoot = newFactory.GetRoot();
    
    var documentRoot = await factoryDocument.GetSyntaxRootAsync().ConfigureAwait(false);
    
    var newRoot= documentRoot.ReplaceNode(document.getRoot(), newFactoryRoot);
    var factorySolution = document.Project.Solution.WithDocumentSyntaxRoot(factoryDocument.Id, newRoot);
    
    

    【讨论】:

      猜你喜欢
      • 2020-12-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-09
      • 2019-02-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多