lundi 18 janvier 2021

c# Altering methods in parsed code in a SyntaxTree

I'm paring a string that contains a c# code using a SyntaxTree. What I would like to do is to alter the methods in the code:

  • Get the list of parameters passed to the method
  • Add lines of code to be executed by the method - some of them has to do with the parameters passed to the method.

This is my code so far:

string code = @"
public void SayHello(string name) {
    Console.WriteLine(""Hello "" + name);
}

private string SayGoodbye() {
    Console.WriteLine(""Goodbye"");
}
";

SyntaxTree syntaxTree = CSharpSyntaxTree.ParseText(code);

var root = syntaxTree.GetRoot();
var members = syntaxTree.GetCompilationUnitRoot().Members;

var firstMember = members[0];
Console.WriteLine(firstMember.ToString());

Console.WriteLine(syntaxTree.ToString());

firstMember contains the tree structure for the SayHello method. Using .ToString() I can get the full method string. From here what I was thinking is to take that string and parse it to get the method parameters and alter the string to add the command lines that I need. And then using reflection read that string code and execute it.

But I was wondering, is there a more correct ".NET" way of doing such alterations parsed code?





Aucun commentaire:

Enregistrer un commentaire