繁体   English   中英

Roslyn语法重写器如何在VisitMethodDeclaration中添加使用伪指令

[英]Roslyn Syntax Rewriter How to add Using Directives from within VisitMethodDeclaration

我正在使用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);
    }
}
        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;
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM