Scope of variables in a delegate

前端 未结 6 1476
醉酒成梦
醉酒成梦 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:26

    You'll also get CS0136 from code like this:

      int i = 0;
      if (i == 0) {
        int i = 1;
      }
    

    The scope of the 2nd declaration of "i" is unambiguous, languages like C++ don't have any beef with it. But the C# language designers decided to forbid it. Given the above snippet, do you think still think that was a bad idea? Throw in a bunch of extra code and you could stare at this code for a while and not see the bug.

    The workaround is trivial and painless, just come up with a different variable name.

提交回复
热议问题