【发布时间】:2021-01-01 11:56:30
【问题描述】:
在下面的代码中,一次只更新一个属性,之前更新的属性将被忽略。我知道语法节点是不可变的,所以我遗漏了一些东西。我最终得到的是只有最后一个被替换的属性被更新。我错过了什么?
var newMemberDeclarations = new SyntaxList<MemberDeclarationSyntax>();
newMemberDeclarations.AddRange(@class.Members);
foreach (var prop in props)
{
var oldProperty = (PropertyDeclarationSyntax)prop;
// e.g. Customer or ICollection<Customer>
if (oldProperty.Type.Kind() == SyntaxKind.IdentifierName ||
oldProperty.Type.Kind() == SyntaxKind.GenericName)
{
var memberAttributes = new SyntaxList<AttributeListSyntax>().AddRange(oldProperty.AttributeLists).Add(jsonIgnoreAttribute);
var newProperty = SyntaxFactory.PropertyDeclaration(
memberAttributes,
oldProperty.Modifiers,
oldProperty.Type,
oldProperty.ExplicitInterfaceSpecifier,
oldProperty.Identifier,
oldProperty.AccessorList
);
var replaced = @class.Members.Replace(oldProperty, newProperty);
// This ignores previously updated property
// and only adds the attribute on the last replaced property
newMemberDeclarations.AddRange(replaced);
}
}
var attributes = @class.AttributeLists.AddRange(attributeLists);
root = root.ReplaceNode(@class, @class.WithAttributeLists(attributes))
.AddUsings(usingSerialization, usingCollections, usingJson)
.WithMembers(newMemberDeclarations)
.NormalizeWhitespace();
【问题讨论】:
标签: c# properties roslyn class-members