c# - 变量破坏范围

标签 c#

这怎么会给出一个 's' does not exist in the current context 错误(正如预期的那样):

public static void Main()
{
    foreach(var i in new[]{1, 2, 3}) {
        int s = i;
    }

    Console.WriteLine(s);
}

( ideone )

但这会产生一个 's' cannot be redeclared 错误?

public static void Main()
{
    foreach(var i in new[]{1, 2, 3}) {
        int s = i;
    }

    int s = 4;
}

( ideone )

第一个错误告诉我 s 不存在于 foreach 之外,这是有道理的,但第二个错误则不然。为什么(以及如何!?)我需要从子作用域访问变量吗?

最佳答案

The first error tells me that s doesn't exist outside of the foreach, which makes sense

确实 - 这是正确的。

but the second error says otherwise.

不,它没有。它告诉您不能声明第一个(嵌套)变量s,因为第二个 已经在范围内。您无法在声明之前访问它,但它在整个 block 的范围内

来自 C# 5 规范,第 3.7 节:

• The scope of a local variable declared in a local-variable-declaration (§8.5.1) is the block in which the declaration occurs.

所以是的,它基本上向上延伸到封闭的 {

然后从 8.5.1 节开始:

The scope of a local variable declared in a local-variable-declaration is the block in which the declaration occurs. It is an error to refer to a local variable in a textual position that precedes the local-variable-declarator of the local variable. Within the scope of a local variable, it is a compile-time error to declare another local variable or constant with the same name.

最后一部分(强调我的)是您收到错误的原因。

Why (and how!?) would I ever need to access a variable from a child scope?

不确定您在这里的意思,但基本规则是让您更难编写难以阅读或脆弱的代码。这意味着向上或向下移动变量声明(但仍在同一 block 中,在同一嵌套级别)产生有效但具有不同含义的代码的地方更少。

关于c# - 变量破坏范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28901520/

相关文章:

c# - 如何在 devexpress 数据网格中包含图像

c# - .NET 5 vNext 使用参数解决依赖关系

c# - 如何将 Epplus 与包含几行的单元格一起使用

c# - vb.net 相当于 "private void (string text)"

c# - 从 C# 运行 64 位编译的 MATLAB 函数

c# - 奇怪的括号行为的 Visual Studio 可能的错误

c# - 遍历列表并将值添加到二维数组

c# - 通过覆盖插件 nopCommerce 3.3 中的 GenericPathRoute.cs 更改 URL 路由

c# - 如何在asp.net mvc中仅显示帖子的前200个字符?

c# - SQL Server 行版本