假设我在语法树中有"".GetType()
ExpressionStatementSyntax
(或者可能是InvocationExpressionSyntax
),我想把它变成("".GetType())
,我想转向我的ExpressionStatementSyntax
节点进入ParenthesizedExpressionSyntax
节点。我该怎么做?
答案 0 :(得分: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());
}
}