Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>[updated for clarity]</p> <p>First; cast the <code>Expression</code> to a <code>MemberExpression</code>.</p> <p>A <code>MemberExpression</code> has two things of interest:</p> <ul> <li>.Member - the <code>PropertyInfo</code> / <code>FieldInfo</code> to the member</li> <li>.Expression - the expression to evaluate to get the "obj" for the .Member</li> </ul> <p>i.e. if you can evaluate the <code>.Expression</code> to "obj", and the <code>.Member</code> is a <code>FieldInfo</code>, then you can get the actual value via <code>.GetValue(obj)</code> on the <code>FieldInfo</code> (and <code>PropertyInfo</code> is very similar).</p> <p>The problem is that evaluating the <code>.Expression</code> is very tricky ;-p</p> <p>Obviously you get lucky if it turns out to be a <code>ConstantExpression</code> - but in most cases it isn't; it could be a <code>ParameterExpression</code> (in which case you'll need to know the actual parameter value that you want to evaluate), or any other combination of <code>Expression</code>s.</p> <p>In many cases, a simple (perhaps lazy) option is to use <code>.Compile()</code> to get the .NET framework to do the heavy lifting; you can then evaluate the lambda as a typed delegate (passing in any parameters that the lambda requires). This isn't always an option, however.</p> <p>To show how complex this is; consider this trivial example (where I've hard-coded at every step, rather than testing etc):</p> <pre><code>using System; using System.Linq.Expressions; using System.Reflection; class Foo { public string Bar { get; set; } } static class Program { static void Main() { Foo foo = new Foo {Bar = "abc"}; Expression&lt;Func&lt;string&gt;&gt; func = () =&gt; foo.Bar; MemberExpression outerMember = (MemberExpression)func.Body; PropertyInfo outerProp = (PropertyInfo) outerMember.Member; MemberExpression innerMember = (MemberExpression)outerMember.Expression; FieldInfo innerField = (FieldInfo)innerMember.Member; ConstantExpression ce = (ConstantExpression) innerMember.Expression; object innerObj = ce.Value; object outerObj = innerField.GetValue(innerObj); string value = (string) outerProp.GetValue(outerObj, null); } } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

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