【发布时间】:2013-12-21 09:36:33
【问题描述】:
我正在尝试向我无法更改的基本类型(例如 Int、Float 或现有/库类型)添加小于或等于方法(非侵入式)。 (见我的另一个问题how to write a generic compare function in Haxe (haxe3))我读到“使用”关键字是这样做的方法。
我打算这样做:
class IntOrder {
static public function le(x:Int,y:Int):Bool { return x <= y; }
}
class FloatOrder {
static public function le(x:Float,y:Float):Bool { return x <= y; }
}
class StringOrder {
static public function le(x:String,y:String):Bool {... }
}
//...Other classes
using IntOrder;
using FloatOrder;
using StringOrder;
//... Other using statements
class Main {
@:generic static public function compare_<A:{function le(y:A):Bool;}>(x:A,y:A): Int {
if (x.le(y) && y.le(x)) return 0;
else if (x.le(y)) return -1;
else se return 1;
}
}
现在 haxe3.01 报错:import and using may not appear after a type declaration。
我知道using 是一种特殊的import 语句,因此可能无法在进行声明的同一文件中导入。
我的问题是:
1) 在像这样的用例中,我是否必须为每个 XXXOrder 类创建一个三行文件?这是相当痛苦的维护。
2) 即使我为每个 XXXOrder 类创建单独的 .hx 文件,相同的函数名称(例如 le)是否会导致名称冲突。
3) 有没有办法绕过 using 关键字(可能使用回调??),以便这些扩展器类可以保存在一个文件中?
提前致谢。
--- 更新 ---
我尝试按照答案中的建议在类定义之前移动 using 语句。现在编译器不会抱怨using 语句。但它抱怨类型检查失败。
using Main.IntOrder;
using Main.FloatOrder;
using Main.StringOrder;
class IntOrder {
static public function le(x:Int,y:Int):Bool { return x <= y; }
}
class FloatOrder {
static public function le(x:Float,y:Float):Bool { return x <= y; }
}
class StringOrder {
static public function le(x:String,y:String):Bool { return true; }
}
class Main {
@:generic static public function compare_<A:{function le(y:A):Bool;}>(x:A,y:A): Int {
if (x.le(y) && y.le(x)) return 0;
else if (x.le(y)) return -1;
else return 1;
}
static public function main() {
Sys.print(compare_(1,2));
}
}
返回:
Main.hx:22: characters 12-25 : Constraint check failure for compare_.A
Main.hx:22: characters 12-25 : Int should be { le : y : Int -> Bool }
x.le(y) 似乎在 compare_ 中仍然不起作用。
【问题讨论】:
标签: generics haxe type-parameter