I'm currently trying to write code that turns C # expressions into text.
To do this, I need to not only go through the Expression tree, but also evaluate only a small part of it - to get the current value of the local variable.
Itβs very difficult for me to put it in words, so instead there is pseudocode. The invalid part is in the first method:
public class Program { private static void DumpExpression(Expression expression) { // how do I dump out here some text like: // set T2 = Perform "ExternalCalc" on input.T1 // I can easily get to: // set T2 = Perform "Invoke" on input.T1 // but how can I substitute Invoke with the runtime value "ExternalCalc"? } static void Main(string[] args) { var myEvaluator = new Evaluator() {Name = "ExternalCalc"}; Expression<Func<Input, Output>> myExpression = (input) => new Output() {T2 = myEvaluator.Invoke(input.T1)}; DumpExpression(myExpression); } } class Evaluator { public string Name { get; set; } public string Invoke(string input) { throw new NotImplementedException("Never intended to be implemented"); } } class Input { public string T1 { get; set; } } class Output { public string T2 { get; set; } }
I started researching this using code:
foreach (MemberAssignment memberAssignment in body.Bindings) { Console.WriteLine("assign to {0}", memberAssignment.Member); Console.WriteLine("assign to {0}", memberAssignment.BindingType); Console.WriteLine("assign to {0}", memberAssignment.Expression); var expression = memberAssignment.Expression; if (expression is MethodCallExpression) { var methodCall = expression as MethodCallExpression; Console.WriteLine("METHOD CALL: " + methodCall.Method.Name); Console.WriteLine("METHOD CALL: " + expression.Type.Name); var target = methodCall.Object;
but as soon as I get to this level of MethodCallExpression, I feel a little lost on how to parse it and then get the actual instance.
Any pointers / suggestions on how to do this are greatly appreciated.
source share