Note that there are some explanatory texts on larger screens.

plurals
  1. POWrap a delegate with a delegate that has a different signature, at runtime (not compile time)
    primarykey
    data
    text
    <p>I'm trying to wrap a lambda Func&lt;bool&gt; with a Func&lt;T,bool&gt; where T is only known at runtime. I'm not looking to actually emit code that does anything with that parameter, it's just going to be ignored and the wrapped method would be called.</p> <p>For instance if I have:</p> <pre><code>Func&lt;bool&gt; innerFunc = () =&gt; true </code></pre> <p>At runtime I need to do something like this:</p> <pre><code>Type paramType = typeof (String); // or any other Type Type wrappedFuncType = typeof (Func&lt;,&gt;).MakeGenericType (paramType, typeof (bool)) // this next line is close to what I want to do but isn't correct Delegate wrappedFunc = Delegate.CreateDelegate (wrappedFuncType, this, innerFunc.Method); </code></pre> <p>I've seen some code using LambdaExpression.Compile which could possibly work, but because this code is in a PCL targeting .NET 4.5, SL4+, WP7+, WinStore it doesn't look like it's available.</p> <p><strong>TL;DR</strong></p> <p>How do I wrap Func&lt;bool&gt; delegate so that it matches something like Func&lt;String,bool&gt; and that calls to the outer delegate returns the value from the inner delegate?</p> <p><strong>UPDATE</strong> Thanks to @usr, I got it working like this:</p> <pre><code>private static Func&lt;T, bool&gt; WrapFuncBool&lt;T&gt; (Func&lt;bool&gt; func) { return _ =&gt; func (); } private Delegate CreateParameterizedFuncBoolDelegate (Type parameterType) { var wrapMethodInfo = this.GetType().GetMethod ("WrapFuncBool", BindingFlags.NonPublic | BindingFlags.Static).MakeGenericMethod (parameterType); return (Delegate) wrapMethodInfo.Invoke (this, new object[] { (Func&lt;bool&gt;) (() =&gt; true) }); } </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. 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