Tôi đang thêm các trường riêng vào một lớp bằng phương thức ClassDeclarationSyntax.AddMembers. Các trường xuất hiện trong lớp, nhưng tôi muốn biết cách thêm các trường vào các vị trí cụ thể. Hiện tại, chúng được thêm vào cuối lớp bên trong #if chỉ thị xảy ra để đánh giá thành đúng tại thời điểm chạy tạo mã.Thêm thành viên lớp vào các vị trí cụ thể bằng Roslyn?
Chạy mã:
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());
sẽ cho kết quả này:
public class A
{
#if !SILVERLIGHT
public int someField;
private string myAddedField;
#endif
}
Và tôi muốn có được kết quả này:
public class A
{
private string myAddedField;
#if !SILVERLIGHT
public int someField;
#endif
}
Tôi không thấy hành vi bạn mô tả. Bạn có thể cho chúng tôi thấy một mẫu mà vấn đề này xuất hiện không? – svick
Xin lỗi, đã sửa câu hỏi của tôi và thêm mã ví dụ. – illodin