Accessing Varibles outside a Lambda (C#)

来源:互联网 发布:蒙古语翻译软件 编辑:程序博客网 时间:2024/06/03 23:45

Lambda expression offers a way to wrap a function without complex definitions.

The compiler creates an anonymous class for a Lambda expression at runtime and creates an instance when it is called. Any variable accessed insided the Lambda will be accessed at the time the instance is created.

int v = 3;Func<int, int> f = s => s+v;v = 5;WriteLine($"The return value of f(0) is {f(0)}");

You may expect a 5 instead of 3.

原创粉丝点击