Note that there are some explanatory texts on larger screens.

plurals
  1. POCall Func<> with argument of type object
    primarykey
    data
    text
    <p>I have (for instance) a <code>Func&lt;int, int&gt;</code> which I want to call as usual, except that the parameter is of type <code>object</code> rater than <code>int</code>. I only know the exact type of the Func and the argument at runtime, because the Func was created using Expression trees and is now accessed from a <code>dynamic</code> variable. (Simplified) code example:</p> <pre><code>using System.Linq.Expressions; namespace FuncExample { class Program { static void Main(string[] args) { object myFunc = CreateFunc(); // Could return something like // Func&lt;int, int&gt;, but may return a // completely different Func&lt;&gt; depending on // arguments etc. object result = getFromFunc(5, myFunc); } public static object CreateFunc() { LambdaExpression expr = Expression.Lambda( /* * Create an expression */ ); return expr.Compile(); } public static object getFromFunc(object arg, object func) { dynamic dynFunc = func; return dynFunc(arg); // &lt;------- Throws exception } } } </code></pre> <p>How can I make the code convert <code>arg</code> into an integer or whatever Type the argument is? I tried making a generic method that casts the object to a certain type and then invoking it through reflection like this:</p> <pre><code>public static T asT&lt;T&gt;(object n) { return (T)n; } </code></pre> <p>for <code>getFromFunc</code>:</p> <pre><code>MethodInfo con = typeof(Program).GetMethod("asT").MakeGenericMethod(func.GetType().GetGenericArguments()[0]); return dfunc(con.Invoke(null, new[] { value })); </code></pre> <p>But <code>MethodInfo.Invoke</code> also returns <code>object</code>. Any ideas on how to make sure the argument has the correct type?</p>
    singulars
    1. This table or related slice is empty.
    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.
 

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