如何使用Roslyn CTP在AttribueList中添加尾行的内容

问题描述 投票:8回答:2

我正试图用 [DataContractAttribute] 使用 Roslyn CTP 语法。不幸的是,Roslyn将属性与属性放在了同一行。

我得到的是这样的结果。

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

我想实现的是:

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

Generator的代码

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

在把这些属性封装在一个类,一个命名空间,最后是CompilationUnit之后,我用下面的代码来获得字符串结果。

var compUnit = Syntax.CompilationUnit().WithMembers(...);
IFormattingResult fResult = compUnit.Format(new FormattingOptions(false, 4, 4));
string result = fResult.GetFormattedRoot().GetText().ToString();
c# .net code-generation roslyn
2个回答
6
投票

一种方法是格式化你的代码,然后通过在所有属性列表中添加尾部的琐事来修改它。就像这样。

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
投票

像下面这样使用。

.WithTrailingTrivia(SyntaxFactory.ElasticCarriageReturnLineFeed)
© www.soinside.com 2019 - 2024. All rights reserved.