在Haxe中,我创建了一个名为MyClass的类,如下所示:
class MyClass {
var score: String;
public function new (score: Int) {
this.score = Std.string(score);
}
public function new (score: String) {
this.score = score;
}
}
我需要多个构造函数,但Haxe不允许我这样做。它从构建阶段抛出此错误:
*.hx:*: lines * : Duplicate constructor
The terminal process terminated with exit code: 1
我怎么解决这个问题?
这称为方法重载,Haxe除extern外不支持(但将来可能会支持)。有多种方法可以解决此问题。
对于构造函数,通常的解决方法是为第二个构造函数使用静态的“工厂方法”:
class MyClass {
var score:String;
public function new(score:String) {
this.score = score;
}
public static function fromInt(score:Int):MyClass {
return new MyClass(Std.string(score));
}
}
您也可以有一个接受两种参数的构造函数:
class MyClass {
var score:String;
public function new(score:haxe.extern.EitherType<String, Int>) {
// technically there's no need for an if-else in this particular case, since there's
// no harm in calling `Std.string()` on something that's already a string
if (Std.is(score, String)) {
this.score = score;
} else {
this.score = Std.string(score);
}
}
}
但是,我不推荐这种方法,因为这种方法haxe.extern.EitherType
本质上是Dynamic
在后台进行的,这对类型安全性和性能不利。同样,EitherType
从技术上讲,它仅适用于外部环境。
类型安全性更高,但也有些冗长的选项是haxe.ds.Either<String, Int>
。在这里,您必须显式调用枚举构造函数:new MyClass(Left("100"))
/ new MyClass(Right(100))
,然后使用模式匹配来提取值。
支持从和进行隐式转换的抽象类型,也可以选择:String
Int
class Test {
static function main() {
var s1:Score = "100";
var s2:Score = 100;
}
}
abstract Score(String) from String {
@:from static function fromInt(i:Int):Score {
return Std.string(i);
}
}
最后,还有一个实验库,它添加了对宏的重载支持,但是我不确定它是否支持构造函数。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句