How to add trailing end of line in AttribueList using Roslyn CTP

I am trying to create multiple properties using [DataContractAttribute] using Roslyn CTP syntax. Unfortunately, Roslyn puts the attribute on the same line as the property.

Here is what I get:

 [DataContract]public int Id { get; set; } [DataContract]public int? Age { get; set; } 

What I would like to achieve:

 [DataContract] public int Id { get; set; } [DataContract] public int? Age { get; set; } 

Generator Code:

 string propertyType = GetPropertyType(); string propertyName = GetPropertyName(); var property = Syntax .PropertyDeclaration(Syntax.ParseTypeName(propertyType), propertyName) .WithModifiers(Syntax.TokenList(Syntax.Token(SyntaxKind.PublicKeyword))) .WithAttributeLists( Syntax.AttributeList( Syntax.SeparatedList<AttributeSyntax>( Syntax.Attribute(Syntax.ParseName("DataContract"))))) .WithAccessorList( Syntax.AccessorList( Syntax.List( Syntax.AccessorDeclaration(SyntaxKind.GetAccessorDeclaration) .WithSemicolonToken(Syntax.Token(SyntaxKind.SemicolonToken)), Syntax.AccessorDeclaration(SyntaxKind.SetAccessorDeclaration) .WithSemicolonToken(Syntax.Token(SyntaxKind.SemicolonToken)) ))); 

After transferring these properties to the class, namespace, and finally CompilationUnit, I use the following code to get the result of the string:

 var compUnit = Syntax.CompilationUnit().WithMembers(...); IFormattingResult fResult = compUnit.Format(new FormattingOptions(false, 4, 4)); string result = fResult.GetFormattedRoot().GetText().ToString(); 
+4
source share
1 answer

One way to do this is to format your code, and then modify it by adding the final little things to all property attribute lists. Sort of:

 var formattedUnit = (SyntaxNode)compUnit.Format( new FormattingOptions(false, 4, 4)).GetFormattedRoot(); formattedUnit = formattedUnit.ReplaceNodes( formattedUnit.DescendantNodes() .OfType<PropertyDeclarationSyntax>() .SelectMany(p => p.AttributeLists), (_, node) => node.WithTrailingTrivia(Syntax.Whitespace("\n"))); string result = formattedUnit.GetText().ToString(); 
+1
source

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


All Articles