[英]Adding class members into specific locations using Roslyn?
我正在使用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
}
為此,您必須找到您想要放置新成員的確切位置,然后相應地修改類成員列表。 就像是:
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.