PhilChuang
PhilChuang

Reputation: 2566

Wrap a delegate with a delegate that has a different signature, at runtime (not compile time)

I'm trying to wrap a lambda Func<bool> with a Func<T,bool> 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.

For instance if I have:

Func<bool> innerFunc = () => true

At runtime I need to do something like this:

Type paramType = typeof (String); // or any other Type
Type wrappedFuncType = typeof (Func<,>).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);

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.

TL;DR

How do I wrap Func<bool> delegate so that it matches something like Func<String,bool> and that calls to the outer delegate returns the value from the inner delegate?

UPDATE Thanks to @usr, I got it working like this:

private static Func<T, bool> WrapFuncBool<T> (Func<bool> func)
{
    return _ => 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<bool>) (() => true) });
}

Upvotes: 4

Views: 2700

Answers (1)

usr
usr

Reputation: 171246

Write the wrapper in C#:

static Func<T, bool> Wrap<T>(Func<bool> f) {
 return _ => f();
}

Now call Wrap using reflection (MakeGenericMethod).

Upvotes: 3

Related Questions