我試圖替換Roslyn語法樹中的節點,它只是工作,但有一個煩惱,感覺它不應該是一個問題。爲什麼SyntaxNode.ReplaceNode更改SyntaxTree選項?
語法樹是從一個腳本生成的,我希望結果也是一個基於腳本的語法樹 - 但由於某種原因,替換樹中的節點會創建一個新的語法樹,其中包含更改的選項:Kind
變成Regular
而不是Script
。這可以用SyntaxTree.WithRootAndOptions
修復,但是如果我需要調用它,感覺就像我做錯了什麼。
樣例程序:
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Scripting;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Scripting;
using System;
using System.Linq;
class Program
{
static void Main(string[] args)
{
Script script = CSharpScript.Create("Console.WriteLine(\"Before\")",
ScriptOptions.Default.AddImports("System"));
var compilation = script.GetCompilation();
var tree = compilation.SyntaxTrees.Single();
var after = SyntaxFactory.LiteralExpression(
SyntaxKind.StringLiteralExpression,
SyntaxFactory.Literal("After"));
var root = tree.GetRoot();
var before = root.DescendantNodes().OfType<LiteralExpressionSyntax>().Single();
var newRoot = root.ReplaceNode(before, after);
var fixedTree = newRoot.SyntaxTree.WithRootAndOptions(newRoot, tree.Options);
Console.WriteLine(newRoot); // Console.WriteLine("After")
Console.WriteLine(tree.Options.Kind); // Script
Console.WriteLine(newRoot.SyntaxTree.Options.Kind); // Regular
Console.WriteLine(fixedTree.Options.Kind); // Script
}
}
(輸出是評論)
這是解決辦法實際上是正確的,或者是有一些不同的方式,我應該更換在樹的節點?
語言版本也發生變化。您必須明確指定是否需要C#5語法樹。我也使用'.WithRootAndOptions()',從來沒有問題。 – Tamas
我的直覺是說這是一個錯誤... –
@JasonMalinowski:我很高興你是那個說 - 我當然不想:)(但是,對我來說也是這樣。 ) –