为什么在 Java 中,变量的作用域限于 switch block 而不是 case block 。例如,
// Scope limited to a switch block
switch (number) {
case 1:
String result = "...";
break;
case 2:
result = "...";
break;
在上面的例子中,result 只需要声明一次。如果您声明它两次,那么您会收到一条 Duplicate local variable
消息。
我的问题是:如果 number = 2
,程序如何知道您声明了 result
?
(它不会落入 case 1
并且不会声明变量...或者会吗?)
编辑:
我可能会让大家感到困惑。我了解如何限制变量的范围,但我的问题是:Java 如何知道如果结果不符合情况则已声明?
最佳答案
编辑:Java 使用词法范围(也称为静态范围),因此变量的范围是在编译时确定的,与实际评估无关。
Java 是 block 作用域的,因此它的作用域将遵循上面示例中的 {}
。
参见 JLS 6.3 :
The scope of a local variable declaration in a block (§14.4) is the rest of the block in which the declaration appears, starting with its own initializer and including any further declarators to the right in the local variable declaration statement.
关于java - 为什么 Java 中的 switch 语句的范围没有限制?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15397492/