简体   繁体   English

如何使用 Roslyn 在命名空间外添加 using 指令?

[英]How to add a using directive outside a namespace using Roslyn?

I have a CSharpSyntaxRewriter that adds a new using directive to my file:-我有一个 CSharpSyntaxRewriter,它向我的文件添加了一个新的 using 指令:-

public class AddUsingDirective : CSharpSyntaxRewriter
{
    public override SyntaxNode VisitNamespaceDeclaration(NamespaceDeclarationSyntax node)
    {
        // this adds the using directive inside the namespace not outside
        node = node.AddUsings(SyntaxFactory.UsingDirective(SyntaxFactory.ParseName("MyCompany.MyProject.DataAccessLayer.Abstractions"))).NormalizeWhitespace();

        return base.VisitNamespaceDeclaration(node);
    }
}

The problem is that is adds the new using directive inside the namespace but I want to add it to the other existing namespaces above the namespace declaration.问题是在命名空间添加了新的 using 指令,但我想将它添加到命名空间声明上方的其他现有命名空间。 Any ideas how I can do this?我有什么想法可以做到这一点?

public override SyntaxNode VisitCompilationUnit(CompilationUnitSyntax node)
{
    // this adds the using directive inside the namespace not outside
    node = node.AddUsings(SyntaxFactory.UsingDirective(SyntaxFactory.ParseName("MyCompany.MyProject.DataAccessLayer.Abstractions"))).NormalizeWhitespace();

    return base.VisitNamespaceDeclaration(node);
}

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

相关问题 如何从Roslyn中的using指令获取完全限定的名称空间? - How can I get the fully qualified namespace from a using directive in Roslyn? 使用 Roslyn 创建命名空间代码重构 - Create Namespace Code Refactoring using Roslyn 如何在格式化的命名空间内移动 using 指令? - How to move the using directive inside the namespace on formatting? 命名空间错误中不存在C#.NET命名空间名称 - 仅当使用在本地命名空间指令之外时 - 为什么? - C#.NET Namespace name does not exist in namespace error - only when using is outside local namespace directive - why? 如何使用Roslyn将第三方DLL添加到CSharp项目中? - How to add a third party DLL to a CSharp Project using Roslyn? 如何使用最新的roslyn API将项目引用添加到另一个项目 - How to add project reference to another Project by using latest roslyn api Roslyn语法重写器如何在VisitMethodDeclaration中添加使用伪指令 - Roslyn Syntax Rewriter How to add Using Directives from within VisitMethodDeclaration 如何使用Roslyn在C#中添加新的运算符 - How to add new operator in C# using Roslyn 如何使用 Roslyn CTP 向 AttribueList 添加行尾 - How to add a trailing end of line to AttribueList using Roslyn CTP 如何使用 Roslyn 将 XML 注释添加到 MethodDeclarationSyntax 节点? - How to add XML Comments to a MethodDeclarationSyntax node using Roslyn?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM