A delegate problem, create delegation in loop

lijie cpunion at gmail.com
Thu Jul 5 20:14:09 PDT 2012


On Thu, Jul 5, 2012 at 4:26 PM, Denis Shelomovskij <
verylonglogin.reg at gmail.com> wrote:


> Different situation is for such C# loop:
> ---
> for (int i = 0; i < funcs.Length; ++i)
> {
>     int t = i;
>     funcs[i] = new MyFunc(() => System.Console.WriteLine(t));
> }
> ---
> where "t" is local for scope. Here C# behaves correctly, but D doesn't.
> This D loop
> ---
> foreach(i; 0 .. 5) {
>     int t = i;
>     functions ~= { printf("%d\n", t); };
> }
> ---
> prints "4" five times. It's Issue 2043:
> http://d.puremagic.com/issues/**show_bug.cgi?id=2043
> <http://d.puremagic.com/issues/show_bug.cgi?id=2043>
>

How to distinguish which variables will be copied to the closure context?

I think this is a scope rule, in the previous code, there are three
variables:
1. function arguments
2. loop variables
3. local variables
Seems only function parameters is copied. In C#, local variables is
copied. There
are other rules? And why is the loop variable not local?

Thanks.

Best regards,

-- Li Jie
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.puremagic.com/pipermail/digitalmars-d/attachments/20120706/639aeceb/attachment.html>


More information about the Digitalmars-d mailing list