简体   繁体   English

如何使用 Roslyn CTP 向 AttribueList 添加行尾

[英]How to add a trailing end of line to AttribueList using Roslyn CTP

I am trying to generate a few properties with [DataContractAttribute] using Roslyn CTP Syntax.我正在尝试使用 Roslyn CTP 语法通过[DataContractAttribute]生成一些属性。 Unfortunately, Roslyn puts the attribute on the same line as the property.不幸的是,Roslyn 将属性与属性放在同一行。

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's 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 wrapping those properties in a class, a namespace and finally CompilationUnit, I am using the following code to get the string result:将这些属性包装在一个类、一个命名空间和最后的 CompilationUnit 中后,我使用以下代码来获取字符串结果:

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

One way to do this would to format your code and then modify it by adding trailing trivia to all property attribute lists.一种方法是格式化您的代码,然后通过向所有属性属性列表添加尾随琐事来修改它。 Something like:就像是:

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();

像下面这样使用它:

.WithTrailingTrivia(SyntaxFactory.ElasticCarriageReturnLineFeed)

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

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