我可以在 Haxe 中为 class 定义隐式转换行为吗?

Can I define implicit cast behaviour for a class in Haxe?

是否可以为 classes 定义隐式转换? 例如,我有一个 class Color:

class Color {
    public var r: Int;
    public var g: Int;
    public var b: Int;

    public function new(?r: Int = 0, ?g: Int = 0, ?b: Int = 0) {
        this.r = r;
        this.g = g;
        this.b = b;
    }
}

如果我有这样的Array<Int>

var myIntegerArray = [255, 0, 255]; // color written in RGB as an array
var c: Color = myIntegerArray; // <= how to make this possible?
trace(c.r);

我在 class 的静态函数上尝试了 @:from:

@:from
static public function fromArray(a: Array<Int>) {
    return new Color(a[0], a[1], a[2]);
}

但编译器对此仍然不满意 (Error: Array<Int> should be Color)。

我知道我可以只使用像 var c = Color.fromArray(myIntegerArray); 这样的静态函数,但我很好奇是否可以隐式转换它。

不,普通 class 的隐式转换是不可能的。但是你有三个解决方案:

  1. 创建 abstract Color(Array<Int>) 而不是 class;

  2. 使用 "chain" 例如class Color > abstract ColorAbs > Array<Int>;

  3. 使用haxe.extern.EitherType<Color, Array<Int>>;

不推荐第二种方案。