gpt4 book ai didi

C# 作用域问题

转载 作者:太空狗 更新时间:2023-10-29 18:21:08 26 4
gpt4 key购买 nike

考虑以下代码示例:

                         // line #
{ // 1
// 2
{ // 3
double test = 0; // 4
} // 5
// 6
double test = 0; // 7
} // 8

这给出了错误

A local variable named 'test' cannot be declared in this scope because it would give a different meaning to 'test', which is already used in a 'child' scope to denote something else

但我不明白为什么?外部测试变量从第 7 行开始而不是第 2 行,那么在第 4 行声明第二个名为 test 的变量的范围在第 5 行结束的问题在哪里?

最佳答案

变量在它们被声明的 block 范围内,它们在哪一行并不重要。

了解 scopes在 C# 语言规范中。

来自规范:

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

和:

Scopes can be nested, and an inner scope may redeclare the meaning of a name from an outer scope. (This does not, however, remove the restriction imposed by Section 3.3 that within a nested block it is not possible to declare a local variable with the same name as a local variable in an enclosing block.)

关于C# 作用域问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3372718/

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