【问题标题】:Roslyn Syntax Rewriter How to add Using Directives from within VisitMethodDeclarationRoslyn 语法重写器如何从 VisitMethodDeclaration 中添加 Using 指令
【发布时间】:2018-03-08 03:32:37
【问题描述】:

我正在使用 Roslyn 重写各种项目中的几种方法,并在某些情况下注入方法参数。这可行,创建类似于以下内容的输出:

GetFilter(Data.Application.Interfaces.IDataSession session, string name)        

我想要它做的是向类添加一个使用指令并添加参数,就像:

GetFilter(IDataSession session, string name)

我查看了几个示例,但我遗漏了一些东西。当我添加以下代码来更新 Using 时,它会停止做任何事情。

public class DbBaseReferencesMethodRewriter : CSharpSyntaxRewriter
{
    public override SyntaxNode VisitMethodDeclaration(MethodDeclarationSyntax node)
    {
        if (RewriterUtility.HasDriveSessionParameter(node)) return node;

        // Start: Add to Using Directives
        var qualifiedName = SyntaxFactory.ParseName("Data.Application.Interfaces");
        var usingDirective = SyntaxFactory.UsingDirective(qualifiedName);
        var rootNode = node.SyntaxTree.GetRoot() as CompilationUnitSyntax;
        rootNode = rootNode.AddUsings(usingDirective).NormalizeWhitespace();
        // End:  Add to Using Directives

        return CreatesDbBaseWithParameterlessConstructor(node)
            ? node.PrependParameter(RewriterUtility.CreateDriveSessionParameter())
            : node;
    }

    private static bool CreatesDbBaseWithParameterlessConstructor(SyntaxNode node)
    {  
        return node.DescendantNodes()
            .OfType<ObjectCreationExpressionSyntax>()
            .Any(RewriterUtility.HasParameterlessDbBaseCall);
    }
}

【问题讨论】:

  • 您创建了一个新的rootNode,但并未将其应用于现有的语法树)

标签: c# roslyn


【解决方案1】:
        private (SyntaxTree, SyntaxTree) UpdateUsingDirectivesForChanges((SyntaxTree, SyntaxTree) change)
    {
        var qualifiedName = SyntaxFactory.ParseName(" Data.Application.Interfaces");
        var usingDirective = SyntaxFactory.UsingDirective(qualifiedName);
        var rootNode = change.Item2.GetRoot() as CompilationUnitSyntax;

        if (!rootNode.Usings.Select(d => d.Name.ToString()).Any(u => u == qualifiedName.ToString()))
        {
            rootNode = rootNode.AddUsings(usingDirective);
            change.Item2 = rootNode.SyntaxTree;
        }

         return change;
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-31
    • 2016-09-20
    • 1970-01-01
    • 2017-03-23
    相关资源
    最近更新 更多