Is it possible to modify a SyntaxTree in Roslyn and run the edited code?

0

Hello,

I am changing a code using Roslyn, however, after the change a new SyntaxNode is generated, but I am not able to find a way to execute this new code. The only one I found was to get the ToString of the new Root and call EvaluateAsync with the new string, but I think it should have a more performative way, since I already have a new code already compiled.

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;
    }
    
asked by anonymous 22.09.2018 / 01:30

0 answers