gpt4 book ai didi

C# 局部变量作用域

转载 作者:太空狗 更新时间:2023-10-29 20:59:13 25 4
gpt4 key购买 nike

<分区>

Possible Duplicate:
confused with the scope in c#

在 C# 中,使用 if/else/loop block 的局部作用域定义的变量似乎与在该 block 之后外部定义的变量冲突 - 请参阅代码片段。等效代码在 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
*/
}

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