The book C # advanced programming mentions that using lambda expressions to access external variables of lambda expressions blocks is a good function (similar to closures in JS ). However, it is very dangerous to use it correctly.
For example
Int someval = 5;
Fun <int, int> F = x => X + someval;
Console. writeline (f (3 ));
Our expression is intended to return the result of a number x + 5. Therefore, the result of F (3) should be 3 + someval = 8.
However, if someval value is accidentally modified in the future, unexpected results will appear.
For example:
Someval = 7;
Console. writeline (f (3 ));
The printed result is 10.
Especially when Lambda is called through multiple threads, we may not know the value of someval at this time, resulting in unpredictable results, so we should use it with caution.
So what is the principle of using external variables in lambda expressions.
Originally, when running a Lambda expression, the compiler creates an anonymous class, which can pass external variables through constructors. The parameters of this constructor depend on the number of variables passed in externally. For the above expression, the anonymous class is as follows:
Public class anonymousclass {
Private int someval;
Public anonymousclass (INT someval) {This. someval = someval ;}
Public int anonymous (int x) {return x + someval ;}
}
In this way, we can understand why lambda expressions can use external variables.
About lambda expressions accessing external variables