C#局部变量范围

luc*_*hon 6 c#

可能重复:
与c#中的范围混淆

看来,在C#的变量与局部范围的if/else /循环块与定义之外的块下面的变量冲突的定义 - 见代码剪断.在C/C++和Java下,等效代码编译得很好.这是C#中的预期行为吗?

public void f(){
  if (true) {
    /* local if scope */
    int a = 1;
    System.Console.WriteLine(a);
  } else {
    /* does not conflict with local from the same if/else */
    int a = 2;
    System.Console.WriteLine(a);
  }

  if (true) {
    /* does not conflict with local from the different if */
    int a = 3;
    System.Console.WriteLine(a);
  }

  /* doing this:
   * int a = 5;
   * results in: Error 1 A local variable named 'a' cannot be declared in this scope
   *  because it would give a different meaning to 'a', which is already used in a 
   *  'child' scope to denote something else
   * Which suggests (IMHO incorrectly) that variable 'a' is visible in this scope
   */

  /* doing this: 
   * System.Console.WriteLine(a);
   * results in: Error 1 The name 'a' does not exist in the current context..
   * Which correctly indicates that variable 'a' is not visible in this scope
   */
}
Run Code Online (Sandbox Code Playgroud)

Ode*_*ded 5

是的,这就是C#的工作原理.

当声明一个范围,从外范围的任何局部变量也称为 - 没有办法来限定,该范围内的局部变量应该从外部覆盖本地变量.