更新时间:2022-12-27 16:22:38
做这种事并不常见,我不会通常这样做。
It is not common practice to do this kind of thing, and I wouldn't do it normally.
这些内部块(即 {...}
)可用于以下几个目的:
Those inner blocks ( i.e. { ... }
) can serve a couple of purposes:
块限制在其中声明的任何变量的范围;例如。
Blocks limit the scope of any variables declared within them; e.g.
public void foo() {
int i = 1;
{
int j = 2;
}
// Can't refer to the "j" declared here. But can declare a new one.
int j = 3;
}
但是,我不建议这样做。 IMO,***使用不同的变量名称或将代码重构为更小的方法。无论哪种方式,大多数Java程序员都会认为 {
和}
是令人讨厌的视觉混乱。
However, I wouldn't recommend doing this. IMO, it's better to use different variable names OR refactor the code into smaller methods. Either way, most Java programmers would regard the {
and }
as annoying visual clutter.
可以使用块来附加标签。
Blocks can be used to attach labels.
HERE : {
...
break HERE; // breaks to the statement following the block
...
}
但是,在实践中,你几乎看不到带标签的断言。而且因为它们非常不寻常,它们往往会使代码的可读性降低。
However, in practice you hardly ever see labelled break statements. And because they are so unusual, they tend to render the code less readable.