Haxe中的常数 [英] Constants in Haxe
问题描述
如何在Haxe中创建公共常量?我只需要AS3中很好的旧 const
的类似物:
How do you create public constants in Haxe? I just need the analog of good old const
in AS3:
public class Hello
{
public static const HEY:String = "hey";
}
推荐答案
在Haxe中声明常量的通常方法是使用 static
和 inline
修饰符.>
The usual way to declare a constant in Haxe is using the static
and inline
modifiers.
class Main {
public static inline var Constant = 1;
static function main() {
trace(Constant);
trace(Test.Constant);
}
}
如果您有一组相关的常数,通常使用枚举摘要
.枚举摘要的值隐式地为 static
和 inline
.
If you have a group of related constants, it can often make sense to use an enum abstract
. Values of enum abstracts are static
and inline
implicitly.
请注意,仅允许使用基本类型( Int
, Float
, Bool
)和 String
成为 inline
,对于其他人,它将因以下错误而失败:
Note that only the basic types (Int
, Float
, Bool
) as well as String
are allowed to be inline
, for others it will fail with this error:
内联变量初始化必须为常数
Inline variable initialization must be a constant value
幸运的是,Haxe 4引入了 final
关键字,在这种情况下非常有用:
Luckily, Haxe 4 has introduced a final
keyword which can be useful for such cases:
public static final Regex = ~/regex/;
但是, final
仅防止重新分配,它不会使类型不可变.因此,仍然有可能从 static final Values = [1、2、3];
之类的值中添加或删除值.
However, final
only prevents reassignment, it doesn't make the type immutable. So it would still be possible to add or remove values from something like static final Values = [1, 2, 3];
.
对于数组的特定情况,Haxe 4引入了 haxe.ds.ReadOnlyArray
允许使用恒定"列表(假设您不使用强制转换或反射方法来解决此问题):
For the specific case of arrays, Haxe 4 introduces haxe.ds.ReadOnlyArray
which allows for "constant" lists (assuming you don't work around it using casts or reflection):
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>
只是创建的抽象类型通过执行以下操作创建只读的视图":
Even though this is an array-specific solution, the same approach can be applied to other types as well. ReadOnlyArray<T>
is simply an abstract type that creates a read-only "view" by doing the following:
- it wraps
Array<T>
- it uses
@:forward
to only expose fields that don't mutate the array, such aslength
andmap()
- it allows implicit casts
from Array<T>
此处.
这篇关于Haxe中的常数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!