繁体   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