Scope of variables in a delegate

前端 未结 6 1512
醉酒成梦
醉酒成梦 2021-01-05 04:53

I found the following rather strange. Then again, I have mostly used closures in dynamic languages which shouldn\'t be suspectable to the same \"bug\". The following makes t

6条回答
  •  Happy的楠姐
    2021-01-05 05:22

    It's because the delegate can reference variables outside the delegate:

    int i = 1;
    VoidFunction t = delegate { Console.WriteLine(i); };
    

提交回复
热议问题