是否可以为类定义隐式强制转换?例如,我有一个课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);
但我很好奇是否可以隐式转换它。
不,对于普通班级进行隐式转换是不可能的。但是您有三种解决方案:
abstract Color(Array<Int>)
代替创建class
;
使用“连锁”,如class Color
> abstract ColorAbs
> Array<Int>
;
使用haxe.extern.EitherType<Color, Array<Int>>
;
我不建议第二种解决方案。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句