Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p> The code that throws the exception is</p> <pre class="lang-csharp prettyprint-override"><code>typeof(Expression).GetMethod("Lambda") </code></pre> <p>because there are 18 methods called <code>Lambda</code> defined on the <code>Expression</code> type (thus the <code>AmbiguousMatchException</code>).</p> <p><code>GetMethod(string methodName)</code> is appropriate when there are no overloads. In this case I would use <code>GetMethods()</code> and then filter out the one I need.</p> <p>In your case, the right overload is</p> <pre class="lang-csharp prettyprint-override"><code>Expression.Lambda&lt;TDelegate&gt;(Expression body, params ParameterExpression[] parameters) </code></pre> <p>You could write a function that validates the right overload by checking the number of parameters and their type, but I found an easier alternative: filter the method by the <code>.ToString()</code> representation, which in our case is:</p> <pre class="lang-csharp prettyprint-override"><code>System.Linq.Expressions.Expression`1[TDelegate] Lambda[TDelegate](System.Linq.Expressions.Expression, System.Linq.Expressions.ParameterExpression[]) </code></pre> <p>There's also a problem with the way you pass the parameters (<code>new object[] { expression, param }</code>). The second parameter is not of type <code>ParameterExpression</code>, but <code>ParameterExpression[]</code> (array), therefore you should pass <code>new[]{param}</code> instead of just <code>param</code>. When calling it in regular code it works like that because it's defined as <code>params ParameterExpression[]</code>.</p> <p>In conclusion, the following code should work in your case:</p> <pre class="lang-csharp prettyprint-override"><code>const string methodSignature = "System.Linq.Expressions.Expression`1[TDelegate] Lambda[TDelegate]" + "(System.Linq.Expressions.Expression, System.Linq.Expressions.ParameterExpression[])"; var lambdaMethod = typeof (Expression).GetMethods() .Single(mi =&gt; mi.ToString() == methodSignature); var funcType = typeof (Func&lt;,&gt;).MakeGenericType(objectType, typeof (object)); var genericLambda = lambdaMethod.MakeGenericMethod(funcType); var selectExpression = genericLambda.Invoke(null, new object[] { expression, new[] { param } }); </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.
 

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