简体   繁体   English

使用Roslyn将类成员添加到特定位置?

[英]Adding class members into specific locations using Roslyn?

I am adding private fields into a class using ClassDeclarationSyntax.AddMembers method. 我正在使用ClassDeclarationSyntax.AddMembers方法将私有字段添加到类中。 Fields appear in the class, but I'd like to know how to add the fields into specific locations. 字段出现在类中,但我想知道如何将字段添加到特定位置。 As of now, they are added at the end of the class inside #if directive that happens to evaluate to true at the time of running the code generation. 截至目前,它们被添加到类的末尾,在#if指令中,在运行代码生成时恰好评估为true。

Running the code: 运行代码:

var tree = SyntaxTree.ParseCompilationUnit(@"
namespace Test
{
    public class A
    {
#if !SILVERLIGHT
        public int someField;
#endif
    }
}");
var field =
    Syntax.FieldDeclaration(
        Syntax.VariableDeclaration(
            Syntax.PredefinedType(
                Syntax.Token(
                    SyntaxKind.StringKeyword))))
    .WithModifiers(Syntax.Token(SyntaxKind.PrivateKeyword))
    .AddDeclarationVariables(Syntax.VariableDeclarator("myAddedField"));
var theClass = tree.GetRoot().DescendantNodes()
    .OfType<ClassDeclarationSyntax>().First();
theClass = theClass.AddMembers(field).NormalizeWhitespace();
System.Diagnostics.Debug.Write(theClass.GetFullText());

will result in this: 会导致这个:

public class A
{
#if !SILVERLIGHT
    public int someField;
    private string myAddedField;
#endif
}

And I would like to get this result: 我想得到这个结果:

public class A
{
    private string myAddedField;
#if !SILVERLIGHT
    public int someField;
#endif
}

To do this, you will have to locate where exactly do you want to place the new member and then modify the list of the class members accordingly. 为此,您必须找到您想要放置新成员的确切位置,然后相应地修改类成员列表。 Something like: 就像是:

private static SyntaxList<MemberDeclarationSyntax> AddBeforeIfDirective(
    SyntaxList<MemberDeclarationSyntax> oldMembers,
    MemberDeclarationSyntax newMember)
{
    var ifIndex = oldMembers.IndexOf(
        member => member.GetLeadingTrivia()
            .Any(t => t.Kind == SyntaxKind.IfDirective));
    return oldMembers.Insert(ifIndex, newMember);
}


…

var newMembers = AddBeforeIfDirective(theClass.Members, field);

theClass = theClass.WithMembers(newMembers).NormalizeWhitespace();

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

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