C#局部变量作用域 [英] C# local variable scope

查看:171
本文介绍了C#局部变量作用域的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

与c#中的范围相混淆

似乎在C#中,使用if / else / loop块的局部作用域定义的变量与在该块之后的外部定义的变量冲突-请参见代码片段。在C / C ++和Java下,等效代码可以很好地编译。这是C#中的预期行为吗?

It appears that in C# a variable defined with the local scope to if/else/loop block is conflicting with variable defined outside following that block - see code snipped. An equivalent code compiles fine under C/C++ and Java. Is this expected behavior in 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
   */
}


推荐答案

是的,这就是C#的工作方式

Yes, this is how C# works.

在声明作用域时,还知道外部作用域中的任何局部变量-无法限定作用域中的局部变量应覆盖局部变量从外面。

When declaring a scope, any local variable from an outer scope is also known - there is no way to qualify that a local variable within the scope should override the local variable from outside.

这篇关于C#局部变量作用域的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆