在 Delphi / Pascal 中有一种机制,通过该机制,方法中的局部变量可以记住从一个方法调用到下一个方法调用的值。这是使用类型化常量完成的。例如:
procedure blah();
const
i: integer = 0;
begin
i := i + 1;
writeln(i);
end;
在每次调用 blah() 时,我都会增加。输出将如下所示:
1 2 3 4 5 ...
(每个数字在不同的行,但这里的编辑器将它们放在同一行)
Java有没有等价的东西?
您可以使用静态变量。在第一次通话时启动一次。并且在每次通话时,他们都会保存最新的值。
public class usingBlah{
static int i = 0;
void blah() {
i++;
//print here by Log.i or whatever
}
}
在这里,就像您在 delphi 中的代码一样, i 在第一次调用时定义并启动。在下一次调用中,它将保存最新值。
May be static variables can help you.
Static variables are initialized just one time when the first instance of the class is being created. After that it stores the value.
Java 中最接近的等价物是类的静态变量。它具有静态生命周期,但也比 Delphi 可分配类型常量具有更广泛的范围。
In Java there is nothing exactly like Delphi's rather quaintly named assignable typed constants that has local scope, but static lifetime. A static class variable is as close as you can get.
In C/C++ you could use a local variable with static storage duration, which has the same semantics as Delphi's assignable typed constants.