Using Roslyn how to update a class using directives?

Just by opening Roslyn, please be patient.

I would like to update the use directives at the top of my class to include an additional element, for example:

using System; public class Foo { } 

It should become:

 using System; using Custom.Bar; public class Foo { } 

I see that I can override SyntaxRewriter , and I did this to process the method level code, but I don’t see an override that could give me access to these directives?

Thanks.

Edit:

I found this property, but I do not know how to change it.

 var tree = document.GetSyntaxTree().GetRoot() as SyntaxNode; var compilationUnitSyntax = (CompilationUnitSyntax) (tree); if (compilationUnitSyntax != null) compilationUnitSyntax.Usings.Add(); 

Unfortunately, UsingDirectiveSyntax is internal, since I can add it !: D

+4
source share
1 answer

To create SyntaxNodes , you must use the Syntax class factory methods in your case, the Syntax.UsingDirective method.

And you can add new usage using AddUsings method something like

 if (compilationUnitSyntax != null) { var name = Syntax.QualifiedName(Syntax.IdentifierName("Custom"), Syntax.IdentifierName("Bar")); compilationUnitSyntax = compilationUnitSyntax .AddUsings(Syntax.UsingDirective(name).NormalizeWhitespace()); } 

Note: due to the immutability of CompilationUnitSyntax you need to reassign the CompilationUnitSyntax variable with the result of calling AddUsings .

+9
source

Source: https://habr.com/ru/post/1488207/


All Articles