【问题标题】:Adding class members into specific locations using Roslyn?使用 Roslyn 将班级成员添加到特定位置?
【发布时间】:2012-09-21 00:51:47
【问题描述】:

我正在使用 ClassDeclarationSyntax.AddMembers 方法将私有字段添加到类中。字段出现在类中,但我想知道如何将字段添加到特定位置。截至目前,它们被添加到 #if 指令内的类末尾,该指令在运行代码生成时恰好评估为 true。

运行代码:

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

将导致:

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

我想得到这个结果:

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

【问题讨论】:

  • 我没有看到你描述的行为。您能否向我们展示出现此问题的示例?
  • 抱歉,解决了我的问题并添加了示例代码。

标签: c# roslyn


【解决方案1】:

为此,您必须确定要放置新成员的确切位置,然后相应地修改类成员列表。比如:

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

【讨论】:

    猜你喜欢
    • 2017-08-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-25
    • 2020-09-11
    • 2011-08-09
    • 1970-01-01
    相关资源
    最近更新 更多