This post takes some of the material we've already covered and mixes it together. We have delegates from part 1, anonymous methods from part 2, automatic closures from parts 3 & 4, and enumerables from part 5. The only thing we are missing is the yield-return construct from part 6. Of course, that is what part 8 is for.
Please start at the beginning of this 8 part series. The answer from part 6 is: 0 1 2.
Here is the code:
class Demo7 // returning a list of delegates, that access a modified closure
{
public Demo7()
{
foreach (var myDelegate in List())
{
Console.Write(myDelegate() + " ");
}
Console.WriteLine("");
}
IEnumerable<MyDelegate> List()
{
var list = new List<MyDelegate>();
for (var j = 0; j < 3; j++)
{
list.Add(delegate { return j++; });
}
return list;
}
}
One item to notice is that List() now returns an enumerable of type MyDelegate instead of an int as we had in part 6. The delegate it returns is an anonymous method which is wrapped in a closure that contains a reference to j. The anonymous method is not executed when it is added to the list, so in theory j should be untouched by the anonymous method throughout the execution of the List() function.
With that reminder, you should be able to easily answer again... What is the output of the above?
>>> Part 8
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.