private async Task <SyntaxNode> ExtractTypeAsync(Document document, CompilationUnitSyntax root, TypeDeclarationSyntax typeDecl, CancellationToken cancellationToken) { var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); var typeSymbol = semanticModel.GetDeclaredSymbol(typeDecl, cancellationToken); var child = typeDecl .Ancestors() .OfType <NamespaceDeclarationSyntax>() .Aggregate( (MemberDeclarationSyntax)typeDecl, (acc, nsDecl) => nsDecl.WithMembers(SyntaxFactory.List(new MemberDeclarationSyntax[] { acc }))); return(root.WithMembers(SyntaxFactory.List(new[] { child }))); }
public static string GetNamespace(Compilation compilation, TypeDeclarationSyntax type) { var space = type.Ancestors().OfType <NamespaceDeclarationSyntax>().FirstOrDefault(); var model = compilation.GetSemanticModel(space.SyntaxTree); var symbol = model.GetDeclaredSymbol(space) as INamespaceSymbol; var names = new List <string>(); do { names.Insert(0, symbol.Name); symbol = symbol.ContainingNamespace; } while (symbol.ContainingNamespace != null); return(string.Join(".", names)); }
public static string?GetNamespace(this TypeDeclarationSyntax typeDeclarationSyntax) => typeDeclarationSyntax .Ancestors() .OfType <NamespaceDeclarationSyntax>() .FirstOrDefault() ?.Name .ToString();