我使用Roslyn的CSharpSyntaxRewriter
来重写以下内容:
string myString = "Hello ";
myString += "World!";
为:
string myString = "Hello ";
myString += "World!"; Log("myString", myString);
我的语法重写器会覆盖VisitAssignmentExpression
,如下所示。
public override SyntaxNode VisitAssignmentExpression(AssignmentExpressionSyntax node)
{
//Construct a new node without trailing trivia
var newNode = node.WithoutTrailingTrivia();
InvocationExpressionSyntax invocation = //Build proper invocation
//Now what? I need to bundle up newNode and invocation and return them
//as an expression syntax
}
我能够"欺骗"通过构造缺少大括号的StatementSyntax
来处理BlockSyntax
时的此限制:
var statements = new SyntaxList<StatementSyntax>();
//Tried bundling newNode and invocation together
statements.Add(SyntaxFactory.ExpressionStatement(newNode));
statements.Add(SyntaxFactory.ExpressionStatement(invocation));
var wrapper = SyntaxFactory.Block(statements);
//Now we can remove the { and } braces
wrapper = wrapper.WithOpenBraceToken(SyntaxFactory.MissingToken(SyntaxKind.OpenBraceToken))
.WithCloseBraceToken(SyntaxFactory.MissingToken(SyntaxKind.CloseBraceToken)
然而,这种方法无法与AssignmentExpressionSyntax
一起使用,因为BlockSyntax
无法投放到ExpressionSyntax
。 (The CSharpSyntaxRewriter tries to make this cast.)
如何将一个SyntaxNode重写为两个SyntaxNodes?
我是否遇到了API的限制,或者有没有类似上述人员可以分享的技巧?
答案 0 :(得分:1)
您需要访问父ExpressionStatementSyntax
并将其替换为BlockSyntax
。
您不能在表达式语句中插入BlockSyntax
作为表达式。