Note that there are some explanatory texts on larger screens.

plurals
  1. POCustom ExpressionTree ToString
    text
    copied!<p>I am trying to create an ExpressionVisitor in order to recreate the expression as the inputed string (with some exception such that capture variable should be displayed as text).</p> <p>I am stuck when I need to visit expression member of expression member. How can I make the following :</p> <pre><code>public class Starter { private static void Main(string[] args) { var test = new SomeClass(); test.EchoTest(); Console.ReadLine(); } } public class SomeClass { public string StringMember { get; set; } public SomeClass Other { get; set; } public void EchoTest() { var capturedString = "localStringValue"; Echo((() =&gt; "hardcodedString"));//Ok : () =&gt; "hardcodedString" Echo((() =&gt; capturedString));//Ok : () =&gt; "localStringValue" (I want the value in this case) Echo((() =&gt; this.StringMember));//Ok : () =&gt; this.StringMember Echo((() =&gt; this.Other.StringMember));//Failed, expected :() =&gt; this.Other.StringMember , received : () =&gt; this.Other.this.Other } private void Echo(Expression&lt;Func&lt;string&gt;&gt; expression) { Console.WriteLine(PathVisitor.GetPath(expression)); } } public class PathVisitor : ExpressionVisitor { private string _path; protected override Expression VisitLambda&lt;T&gt;(Expression&lt;T&gt; node) { Visit(node.Body); _path = string.Format("() =&gt; {0}", _path); return node; } protected override Expression VisitConstant(ConstantExpression node) { _path = string.Format("\"{0}\"", node.Value); return node; } protected override Expression VisitMember(MemberExpression node) { var generatedClass = null != Attribute.GetCustomAttribute(node.Expression.Type, typeof(CompilerGeneratedAttribute)); if (node.Expression.NodeType == ExpressionType.Constant &amp;&amp; generatedClass) { var getter = Expression.Lambda(node); //let's eval captured Variable _path = string.Format("\"{0}\"", getter.Compile().DynamicInvoke()); } else if (node.Expression.NodeType == ExpressionType.Constant) { _path = string.Format("this.{0}", node.Member.Name); } else { base.Visit(node.Expression); var callerPath = _path; _path = string.Format("{0}.{1}", callerPath, _path); } return node; } public static string GetPath(Expression expression) { var visitor = new PathVisitor(); visitor.Visit(expression); return visitor._path; } } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload