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

问题描述 投票:1回答:1

是否可以为类定义隐式转换?例如,我有一个类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);

我在班上的静态函数上尝试了@: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 casting haxe implicit
1个回答
2
投票

不,普通班级的隐式演员是不可能的。但是你有三个解决方案:

  1. 创建abstract Color(Array<Int>)而不是class;
  2. 使用“链”,例如class Color> abstract ColorAbs> Array<Int>;
  3. 使用haxe.extern.EitherType<Color, Array<Int>>;

我不推荐第二种解决方案。

© www.soinside.com 2019 - 2024. All rights reserved.