问题
I'm using Roslyn's CSharpSyntaxRewriter to rewrite the following:
string myString = "Hello ";
myString += "World!";
to:
string myString = "Hello ";
myString += "World!"; Log("myString", myString);
My syntax rewriter overrides VisitAssignmentExpression
as follows.
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
}
I have been able to "cheat" this limitation when dealing with StatementSyntax
by constructing a BlockSyntax
with missing braces:
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)
However this approach won't work with AssignmentExpressionSyntax
as BlockSyntax
cannot be cast to ExpressionSyntax
. (The CSharpSyntaxRewriter tries to make this cast.)
How can I rewrite one SyntaxNode into two SyntaxNodes?
Have I run up against a limitation of the API, or are there any tricks similar to the above that someone could share?
回答1:
You need to visit the parent ExpressionStatementSyntax
and replace that with a BlockSyntax
.
You cannot insert a BlockSyntax
as an expression in an expression statement.
来源:https://stackoverflow.com/questions/28802121/rewrite-syntaxnode-to-two-syntaxnodes