ROSYLNC#代码修复不删除多个节点

问题描述 投票:0回答:0
private async Task<Document> ApplyCodeFixAsync(Document document, MethodDeclarationSyntax methodDeclaration, CancellationToken cancellationToken) { var root = await document.GetSyntaxRootAsync(cancellationToken); var classDeclaration = methodDeclaration.FirstAncestorOrSelf<ClassDeclarationSyntax>(); var propertyName = LegacyPropertyAnalyzer.GetPropertyNameFromMethod(methodDeclaration.Identifier.Text); if (classDeclaration == null) return document; // Find the setter method var setterMethodDeclaration = classDeclaration.Members .OfType<MethodDeclarationSyntax>() .FirstOrDefault(m => m.Identifier.Text.Equals("set" + propertyName, StringComparison.InvariantCultureIgnoreCase)); // Find the getter method (if needed) var getterMethodDeclaration = classDeclaration.Members .OfType<MethodDeclarationSyntax>() .FirstOrDefault(m => m.Identifier.Text.Equals("get" + propertyName, StringComparison.InvariantCultureIgnoreCase)); var propertyDeclaration = classDeclaration.Members .OfType<PropertyDeclarationSyntax>() .FirstOrDefault(p => p.Identifier.Text.Equals(propertyName, StringComparison.InvariantCultureIgnoreCase)); var fieldDeclaration = LegacyPropertyAnalyzer.GetFieldFromPropertyMethod(methodDeclaration); if (fieldDeclaration != null) { // Remove the field root = root.RemoveNode(fieldDeclaration, SyntaxRemoveOptions.KeepNoTrivia); } if (setterMethodDeclaration != null) { // Remove the setter method root = root.RemoveNode(setterMethodDeclaration, SyntaxRemoveOptions.KeepNoTrivia); } if (getterMethodDeclaration != null) { // Remove the getter method root = root.RemoveNode(getterMethodDeclaration, SyntaxRemoveOptions.KeepNoTrivia); } if (propertyDeclaration != null) { // Remove the property root = root.RemoveNode(propertyDeclaration, SyntaxRemoveOptions.KeepNoTrivia); } // Return the document with the updated root return document.WithSyntaxRoot(root); }

对单元测试进行启动,我可以看到代码修复已输入并root.removenode(...)多次称为删除多个元素。 给定以下测试代码:

class TestMethod2 { private int prop1; public int getProp1() { return prop1; } public void setProp1(int prop1) { this.prop1 = prop1; } public int Prop1 { get => prop1; set => this.prop1 = value; } public void foo() { var x = getProp1(); setProp1(42); } }

我希望除了foo()以外的所有内容。 wo,单位测试失败,声称并非所有内容都已被删除。
代码仅删除仅字段,而不是方法和属性

如果我禁用removenode(fieldDeclaration,...),它将删除get和设置方法,而不是属性(和ofc而不是字段)
如果我还禁用方法上的removenode,它将删除属性

有人可以解释这种行为吗?我真的很困惑。

我知道还有一个removenodes()选项并立即通过所有节点确实有效,但这不是我的关键问题,因为特定的代码修复只是一个例子。应该有一种正确的方法来删除 - 或更改/添加 - 多个步骤中的多个节点。
  • Syntax树是不变的。一旦做到,您就会得到一棵新的语法树。然后,您随后的removenode调用传递了一个不再存在的节点。 您可以使用语法编辑器,从而在多个更改中正确跟踪节点。
roslyn
最新问题
© www.soinside.com 2019 - 2025. All rights reserved.