假设我在语法树中有 "".GetType()
which is ExpressionStatementSyntax
(或者可能是InvocationExpressionSyntax
),我想把它变成("".GetType())
,也就是说我想把我的 ExpressionStatementSyntax
节点变成ParenthesizedExpressionSyntax
节点。我该怎么做?
问问题
462 次
1 回答
3
using System;
using System.Linq;
using Roslyn.Compilers;
using Roslyn.Compilers.CSharp;
class Program
{
static void Main(string[] args)
{
var oldRootNode = Syntax.ParseCompilationUnit(
"class C { void M() { \"\".GetType(); } }");
var oldStatementNode = oldRootNode.DescendantNodes().OfType<ExpressionStatementSyntax>().First();
var oldExpressionNode = oldStatementNode.Expression;
var newExpressionNode = Syntax.ParenthesizedExpression(oldExpressionNode);
var newRootNode = oldRootNode.ReplaceNode(oldExpressionNode, newExpressionNode);
Console.WriteLine(oldRootNode.ToString());
Console.WriteLine(newRootNode.ToString());
}
}
于 2012-08-27T20:31:38.363 回答