gpt4 book ai didi

c# - if 内的作用域变量

转载 作者:行者123 更新时间:2023-11-30 17:13:12 42 4
gpt4 key购买 nike

<分区>

Possible Duplicate:
C# Variable Scoping

我想我可以在不同的范围内声明两个同名的变量:

namespace IfScope
{
class Demo
{
public static void Main()
{
bool a = true;

if ( a )
{
int i = 1;
}
string i = "s";
}
}
}

编译器说了些别的:

$ csc Var.cs
Microsoft (R) Visual C# 2010 Compiler version 4.0.30319.1
Copyright (C) Microsoft Corporation. All rights reserved.

Var.cs(13,20): error CS0136: A local variable named 'i' cannot be declared in this scope because it would give a different meaning to 'i', which is already used in a 'child' scope to denote something else

这意味着在 if 内部声明的 i 在外部可见(这就是我的理解)

但如果我尝试使用它,那么我就会明白这一点。

$ cat Var.cs
namespace IfScope
{
class Demo
{
public static void Main()
{
bool a = true;

if ( a )
{
int i = 1;
}
i = "s";
}
}
}

Var.cs(13,14): error CS0103: The name 'i' does not exist in the current context

很明显,但是这里发生了什么?

42 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com