ClassDeclarationSyntax.AddMembers メソッドを使用してクラスにプライベート フィールドを追加しています。フィールドはクラスに表示されますが、フィールドを特定の場所に追加する方法を知りたいです。現時点では、コード生成の実行時にたまたま true と評価される #if ディレクティブ内のクラスの最後に追加されています。
コードの実行:
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
}