在 CodeFixProvider 我需要删除包装 if 条件(例如):
if (temp == null)
{
temp = new Temp();
}
我只想留下调整后的内部表达:
// I want to change the inner expression as well
temp = anotherTemp()
一旦我尝试用 line-line 语句替换 'if-block' 的节点,就会抛出 'unable to cast' 异常。你知道正确的做法吗?
在 CodeFixProvider 我需要删除包装 if 条件(例如):
if (temp == null)
{
temp = new Temp();
}
我只想留下调整后的内部表达:
// I want to change the inner expression as well
temp = anotherTemp()
一旦我尝试用 line-line 语句替换 'if-block' 的节点,就会抛出 'unable to cast' 异常。你知道正确的做法吗?
我发现的唯一解决方案是在 if-condition 块之前插入调整后的内部表达式,然后删除该块。要成功做到这一点,您必须跟踪父块节点,否则它将无法工作。
IfStatementSyntax originalIfStatement = parentIfStatement;
root = root.TrackNodes(originalParentIfStatement);
parentIfStatement = root.GetCurrentNode(originalParentIfStatement);
root = root.InsertNodesBefore(parentIfStatement, new[] { SyntaxFactory.ExpressionStatement(newExpression) });
parentIfStatement = root.GetCurrentNode(originalParentIfStatement);
root = root.RemoveNode(parentIfStatement, SyntaxRemoveOptions.KeepNoTrivia);
如果有人看到任何错误,请告诉我。