Haxe中的常数 [英] Constants in Haxe

查看:63
本文介绍了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:

  • 它包装 Array< T>
  • 它使用 @:forward 来仅公开不更改数组的字段,例如 length map()
  • 它允许隐式强制转换 来自Array< T>
  • it wraps Array<T>
  • it uses @:forward to only expose fields that don't mutate the array, such as length and map()
  • it allows implicit casts from Array<T>

此处.

这篇关于Haxe中的常数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆