簡體   English   中英

Roslyn:將 using 語句添加到語法樹

[英]Roslyn: Add using statements to Syntax tree

我已經成功創建了一個代碼修復,如果它們從通用工廠類中丟失,它會生成工廠方法。 當我查看已修復的文件時,由於缺少 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 指令?

我最終打破了我的代碼。 這兩個都有效:

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

請注意,第二個替換了 using。

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM