我在SO上看过其他一些类似的问题,但是它们似乎并未专门解决以下问题。
我要实现的是拥有无法更改的编译时常量。
我有一个程序,为了使代码整洁,我对其进行了一些重组。该程序在“ main()”之前有一些const声明。我将它们移到了一个类上,但是要求将它们声明为“ static const”。然后我想,好吧,在“ main()”之前的其他“ const”声明也应该是“ static const”。但是,当我尝试这样做时,编辑器建议“不能将顶级声明声明为'static'”。例如。
static const int I_CORRECT_YN = 12; // prompt nr.
Run Code Online (Sandbox Code Playgroud)
所以,我有点困惑。我认为“常量”是静态的。为什么我必须在该类中声明“静态”?为什么不能将“顶级” const声明为“静态”?另外,两者之间有什么区别?
static const int I_CORRECT_YN = 12;
const int I_CORRECT_YN = 12;
static final int I_CORRECT_YN = 12;
final int I_CORRECT_YN = 12; ?
Run Code Online (Sandbox Code Playgroud)
声明不能更改的编译时值的最佳或唯一方法是什么?
我想我在看字面意思,但我认为还有一个更复杂的意思。
为什么我必须在该类中声明“静态”?
因为实例变量/方法不能是const。这将意味着它们的值可能因实例而异,而编译时常量则并非如此。(资源)
为什么不能将“顶级” const声明为“静态”?
所述static改性剂的标记变量/方法作为类宽(对于类的每个实例相同的值)。顶级内容是应用程序范围的,并且不属于任何类,因此将它们标记为类范围的内容没有任何意义,也是不允许的。(资源)
声明不能更改的编译时值的最佳或唯一方法是什么?
您已经在做- static在定义类常量时添加。定义顶级常量时不要添加它。另外,请使用const。finalvar不是编译时值。
[省略了具有不同常量定义的源代码]之间有什么区别
static const并且const是几乎相同的,使用取决于上下文。之间的差const和final是,const是编译时间常数-他们只能使用文字值(或者表达式constisting运营商和文字值的)进行初始化,并且不能被改变。final变量在初始化后也无法更改,但它们基本上是普通变量。这意味着可以使用任何类型的表达式,并且每个类实例的值可以不同:
import "dart:math";
Random r = new Random();
int getFinalValue() {
return new Random().nextInt(100);
}
class Test {
// final variable per instance.
final int FOO = getFinalValue();
// final variable per class. "const" wouldn't work here, getFinalValue() is no literal
static final int BAR = getFinalValue();
}
// final top-level variable
final int BAZ = getFinalValue();
// again, this doesn't work, because static top-level elements don't make sense
// static final int WAT = getFinalValue();
void main() {
Test a = new Test();
print(Test.BAR);
print(BAZ); // different from Test.BAR
print(a.FOO);
a = new Test();
print(Test.BAR); // same as before
print(BAZ); // same as before
print(a.FOO); // not the same as before, because it is another instance,
// initialized with another value
// but this would still be a syntax error, because the variable is final.
// a.FOO = 42;
}
Run Code Online (Sandbox Code Playgroud)
我希望这会有所帮助,而且我也不会感到困惑。:]
| 归档时间: |
|
| 查看次数: |
425 次 |
| 最近记录: |