我正在使用Roslyn語法樹來更新if/else語句。這裏是我的代碼:Roslyn IfStatement
foreach (StatementSyntax statement in blockNode.Statements)
{
if (statement.IsKind(SyntaxKind.IfStatement))
{
BlockSyntax ifBlock = statement.ChildNodes().OfType<BlockSyntax>().FirstOrDefault();
if (ifBlock != null)
{
ReturnStatementSyntax newRSS = ifBlock.ChildNodes().OfType<ReturnStatementSyntax>().FirstOrDefault();
blockNode = blockNode.InsertNodesBefore(newRSS, newExitCode);
}
ElseClauseSyntax elseBlock = statement.ChildNodes().OfType<ElseClauseSyntax>().FirstOrDefault();
if (elseBlock != null)
{
BlockSyntax block = elseBlock.ChildNodes().OfType<BlockSyntax>().FirstOrDefault();
if (block != null)
{
ReturnStatementSyntax newRSS = block.ChildNodes().OfType<ReturnStatementSyntax>().FirstOrDefault();
blockNode = blockNode.InsertNodesBefore(newRSS, newExitCode);
}
}
newBlock = newBlock.AddRange(blockNode.Statements);
}
}
任何人都可以解釋爲什麼第一個blockNode插入節點的作品,但第二個不?我看到了我要插入的代碼,但只有第一個更新語法樹。第二個什麼都不做。
更新:我做了JoshVarty建議的更改。我使用DocumentEditor來加載更改。當我調用GetChangedDocument時,我現在得到一個異常。這裏是我的代碼:
DocumentEditor editor = DocumentEditor.CreateAsync(doc).Result;
editor.InsertBefore(blockNode, newEntryCode);
editor.InsertAfter(blockNode, newExitCode);
Document newDoc = editor.GetChangedDocument();
唯一的例外是:「System.InvalidOperationException」類型的異常出現在Microsoft.CodeAnalysis.CSharp.dll但在用戶代碼
其他信息沒有處理:指定的項目不是列表的元素。
我必須使用發生器嗎?我錯過了什麼?
感謝
另一種選擇是明確使用重寫器,並執行單個自底向上重寫通過。 –