Created
February 1, 2015 08:01
-
-
Save ufcpp/62c624b56a7dcd25ea15 to your computer and use it in GitHub Desktop.
Local variable captured by lambda
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
class Program | |
{ | |
static void Main() | |
{ | |
var f = X(); | |
Console.WriteLine(f(1)); // 1 (value += 1) | |
Console.WriteLine(f(2)); // 3 (value += 2) | |
Console.WriteLine(f(3)); // 6 (value += 3) | |
} | |
static Func<int, int> X() | |
{ | |
int value = 0; // ローカルな変数に見えて… | |
return x => value += x; // こいつのせいで外から書き替えられる | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment