Scope of variables in a delegate

前端 未结 6 1535
醉酒成梦
醉酒成梦 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条回答
  •  没有蜡笔的小新
    2021-01-05 05:25

    Actually, the error doesn't seem to have anything to do with anonymous delegates or lamda expressions. If you try to compile the following program ...

    using System;
    
    class Program
    {
        static void Main()
        {
            // Action t = delegate
            {
                int i = 0;
            };
    
            int i = 1;
        }
    }
    

    ... you get exactly the same error, no matter whether you comment in the line or not. The error help shows a very similar case. I think it is reasonable to disallow both cases on the grounds that programmers could confuse the two variables.

提交回复
热议问题