在 Haxe 中声明常量的常用方法是使用static
and inline
修饰符。
class Main {
public static inline var Constant = 1;
static function main() {
trace(Constant);
trace(Test.Constant);
}
}
如果您有一组相关的常量,那么使用enum abstract https://haxe.org/manual/types-abstract-enum.html。枚举摘要的值为static
and inline
隐含地。
请注意,只有基本类型(Int
, Float
, Bool
) 也String
被允许inline
,对于其他人来说,它将失败并出现以下错误:
内联变量初始化必须是常量值
幸运的是,Haxe 4 引入了final
对于这种情况可能有用的关键字:
public static final Regex = ~/regex/;
然而,final
只能防止重新分配,它不会使类型不可变。因此仍然可以添加或删除类似的值static final Values = [1, 2, 3];
.
对于数组的具体情况,Haxe 4 引入了haxe.ds.ReadOnlyArray https://api.haxe.org/v/development/haxe/ds/ReadOnlyArray.html?它允许“常量”列表(假设您不使用强制转换或反射来解决它):
public static final Values:haxe.ds.ReadOnlyArray<Int> = [1, 2, 3];
Values = []; // Cannot access field or identifier Values for writing
Values.push(0); // haxe.ds.ReadOnlyArray<Int> has no field push
尽管这是特定于数组的解决方案,但相同的方法也可以应用于其他类型。ReadOnlyArray<T>
简单来说就是一个抽象类型 https://haxe.org/manual/types-abstract.html通过执行以下操作创建只读“视图”:
- 它包裹着
Array<T>
- it uses @:forward https://haxe.org/manual/types-abstract-forward.html仅公开不会改变数组的字段,例如
length
and map()
- 它允许隐式转换 https://haxe.org/manual/types-abstract-implicit-casts.html
from Array<T>
你可以看看它是如何实现的here https://github.com/HaxeFoundation/haxe/blob/development/std/haxe/ds/ReadOnlyArray.hx.