When I worked through this example in my head I got an output of 4 8 3
. When I run the function however I get the output 4 8 6
, I understand how to get the 4
and the 8
but I can't understand how y = 6
. Shouldn't y = 3
? a1
runs which results in y +=1
so y = 1
then a2
runs which results in y+=2
so y = 3
.
void Main() {
int y = 0;
Func<int,bool> even = (n) => { return n%2 == 0; };
Func<int,int> dub = (n) => { y += 2; return n + n; };
Func<int,int> succ = (n) => { y += 1; return n + 1; };
Func<bool, int, int, int> if1 = (c, t, f) => c? t: f;
y = 0;
var a1 = if1(even(3), dub(3), succ(3));
var a2 = if1(even(4), dub(4), succ(4));
Console.WriteLine("{0} {1} {2}", a1, a2, y);
}
Eventhough you have a conditional expression in if1
that will only use t
or f
, the values send into if1
are always calculated before the call.
To only calculate the values when needed, you would send in delegates to the function, not values:
Func<bool, Func<int>, Func<int>, int> if1 = (c, t, f) => c ? t() : f();
y = 0;
var a1 = if1(even(3), () => dub(3), () => succ(3));
var a2 = if1(even(4), () => dub(4), () => succ(4));
What you have to realize here is that the two calls to if1
are passed the return values of dub
and succ
(because you actually call them).
var a1 = if1(even(3), dub(3), succ(3));
var a2 = if1(even(4), dub(4), succ(4));
That means that regardless of whether or not the return value is used (as determined by if1
) the methods have run, and modified y
. That is why it is 6, as both dub
and succ
were called twice by the program, and 2+2+1+1=6
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.