C# 是否可以在Roslyn中修改SyntaxTree并运行已编辑的代码?

C# 是否可以在Roslyn中修改SyntaxTree并运行已编辑的代码?,c#,roslyn,C#,Roslyn,我正在使用Roslyn更改一个代码,但是,更改后会生成一个新的SyntaxNode,但我无法找到执行此新代码的方法。我找到的唯一方法是从新的根中获取ToString,并使用新字符串调用evaluatesync。应该有一种方法比这更好,因为我已经编译了一段新代码 static void Main(string[] args) { var expression = "System.Console.WriteLine(\"Test\")"; var compile = CSharpSc

我正在使用Roslyn更改一个代码,但是,更改后会生成一个新的
SyntaxNode
,但我无法找到执行此新代码的方法。我找到的唯一方法是从新的
中获取
ToString
,并使用新字符串调用
evaluatesync
。应该有一种方法比这更好,因为我已经编译了一段新代码

static void Main(string[] args)
{
    var expression = "System.Console.WriteLine(\"Test\")";
    var compile = CSharpScript.Create<EntityRepresentation>(expression).GetCompilation();
    var root = compile.SyntaxTrees.Single().GetRoot();

    var descentands = root.DescendantNodes().Where(n =>
    {
        if (n is ArgumentSyntax)
            return true;
        return false;
    }).ToList();

    var otherRoot = root.ReplaceNodes(descentands, (n1, n2) =>
    {
        var argumentName = Argument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal("NewValue")));
        return argumentName;
    });

    var newCode = otherRoot.ToString();

    // Faz o que estou querendo, contudo não me parece a melhor maneira
    var result = CSharpScript.EvaluateAsync(newCode).Result;
}
static void Main(字符串[]args)
{
var expression=“System.Console.WriteLine(\“Test\”);
var compile=CSharpScript.Create(expression).getcompile();
var root=compile.SyntaxTrees.Single().GetRoot();
var descentands=root.DescendantNodes()。其中(n=>
{
if(n是ArgumentSyntax)
返回true;
返回false;
}).ToList();
var otherRoot=root.ReplaceNodes(descentands,(n1,n2)=>
{
var argumentName=参数(LiteralExpression(SyntaxKind.StringLiteralExpression,Literal(“NewValue”));
返回参数名;
});
var newCode=otherRoot.ToString();
//这是一个很好的选择,但我不知道该怎么做
var result=CSharpScript.evaluatesync(newCode.result);
}

从语法树创建脚本对象的方法不幸是Microsoft程序集的内部方法

但是,您不必编译两次——您可以第一次解析,然后第二次编译

var expression = "System.Console.WriteLine(\"Test\")";
var origTree = CSharpSyntaxTree.ParseText(expression, 
                  CSharpParseOptions.Default.WithKind(SourceCodeKind.Script));
var root = origTree.GetRoot();

// -Snip- tree manipulation

var script = CSharpScript.Create(otherRoot.ToString());
var errors = script.Compile();
if(errors.Any(x => x.Severity == DiagnosticSeverity.Error)) {
    throw new Exception($"Compilation errors:\n{string.Join("\n", errors.Select(x => x.GetMessage()))}");
}
await script.RunAsync();