Closure Example
Example 1:
static Func
{
int seed = 0;
return () => seed++; // Returns a closure
}
static void Main()
{
Func
Console.WriteLine (natural()); // 0
Console.WriteLine (natural()); // 1
}
Example 2:
static Func
{
return() => { int seed = 0; return seed++; };
}
static void Main()
{
Func
Console.WriteLine (natural()); // 0
Console.WriteLine (natural()); // 0
}
Capturing is internally implemented by “hoisting” the captured
variables into fields of a private class. When the method is
called, the class is instantiated and lifetime-bound to the delegate
instance.
0 Comments:
Post a Comment
<< Home