a = …; Func

How to compose two lambdas of type "delegate" in C #

Let's say we have defined two Lambdas.

Func<TInput, TOutput> a = …;
Func<TInput1, TInput2, TOutput> b = …;

      

Now let's assume we have some code that doesn't work with generics and receives these Lambdas as delegates not yet introduced.

delegate da = a;
delegate db = b;

      

In this code, we want to link two lambdas / delegates to a new, composed lambda, for example. (i1, i2) => b(a(i1), i2)

but a and b are not available, only da and db are available. How can this be done in an elegant way?

+3


source to share


1 answer


Is this what you want?:

Func<int, int> a = p0 => p0 << 1;
Func<int, int, int> b = (p0, p1) => p0 + p1;

Delegate da = a;
Delegate db = b;

var inner = da.Method.GetParameters().Length < db.Method.GetParameters().Length ? da : db;
var outer = inner == da ? db : da;

Func<int, int, int> c = (i1, i2) => (int)outer.DynamicInvoke(inner.DynamicInvoke(i1), i2);

      



I would prefer to create an expression tree to create a new lambda created as you wish. Perhaps there is the logic needed to determine which argument should be passed to a

, and at which parameter the result should be a

passed to b

.

Is it the way you want it?

+4


source







All Articles