4
我正在编写一个代码分析器,它将if语句反转以减少嵌套。Roslyn在指定节点后插入节点
我能够生成一个新的if节点并将其替换为文档根目录。不过,我必须将所有来自if语句的内容(语句)移到下面。让我告诉我到目前为止已经取得的成就:
var ifNode = @if;
var ifStatement = @if.Statement as BlockSyntax;
var returnNode = (ifNode.Parent as BlockSyntax).Statements.Last() as ReturnStatementSyntax ?? SyntaxFactory.ReturnStatement();
var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
var invertedIf = ifNode.WithCondition(Negate(ifNode.Condition, semanticModel, cancellationToken))
.WithStatement(returnNode)
.WithAdditionalAnnotations(Formatter.Annotation);
var root = await document.GetSyntaxRootAsync(cancellationToken);
var newRoot = root.ReplaceNode(ifNode, invertedIf);
newRoot = newRoot.InsertNodesAfter(invertedIf, ifStatement.Statements); //It seems no to be working. There's no code after specified node.
return document.WithSyntaxRoot(newRoot);
前:
public int Foo()
{
if (true)
{
var a = 3;
return a;
}
return 0;
}
后:
public int Foo()
{
if (false)
return 0;
var a = 3;
return a;
}
这有点难(可能只是为了我)看看你想达到什么目的。你能提供一个你想要达到的事情吗? – JoshVarty
正如@JoshVarty问之前/之后有一个例子。 – Gandarez
你是怎么做@If语法的? – MHGameWork