扩展@clemos 的回答——不可能像使用简单的 typedef 一样对待类字段和属性,因为 Haxe getter 和 setter 在编译时被解析——有另一种方法来处理这个问题。
不过,这有点麻烦。你可以在here看到它。
首先,我们在一个同时使用变量和属性的包装器上构建一个抽象:
// let's start with our possible point types
typedef NoGetters = { x:Float, y:Float };
typedef WithProperties = { var x(get,set):Float; var y(get,set):Float; };
// now, let's prepare a common implementation for them
typedef SomePoint2Impl<T> = { obj:T, get_x:Void->Float, get_y:Void->Float };
// and use it in and abstract
abstract SomePoint2<T>(SomePoint2Impl<T>) from SomePoint2Impl<T> {
// these wrap points in the common type
@:from static function fromNoGetters<T:NoGetters>(p:T):SomePoint2<T>
return { obj : p, get_x : function () return p.x, get_y : function () return p.y };
@:from static function fromWithProperties<T:WithProperties>(p:T):SomePoint2<T>
return { obj : p, get_x : function () return p.x, get_y : function () return p.y };
// and this restores the original type from the common one
@:to function toOriginal():T
return this.obj;
}
现在我们在原始nearest 方法的简化Point->Point 版本中使用此摘要并对其进行测试。
// a test class for points with properties
// (points without properties can be tested with anonymous structs)
// don't use @:isVar, so that is clear that the getter was called
class TestPoint {
var _x:Float;
var _y:Float;
public var x(get,set):Float;
function get_x() return _x;
function set_x(x) return _x = x;
public var y(get,set):Float;
function get_y() return _y;
function set_y(y) return _y = y;
public function toString()
return '(x:$x, y:$y)';
public function new(x,y)
{
_x = x;
_y = y;
}
}
class Test {
// a simplified function that takes some "point" and returns it back
// it retains the basic type system problem as `nearest`
public static function test<T>(p:SomePoint2<T>)
return p;
static function main()
{
// some points
var p1 = { x:1., y:2. };
var p2 = new TestPoint(1, 2);
// calls to test
var t1 = test(p1);
var t2 = test(p2);
$type(t1);
$type(t2);
// show that identity has been preserved
// t1,t2 both get cast back to their original types
trace(t1 == p1);
trace(t2 == p2);
// show explicit conversions
trace((t1:{x:Float, y:Float}));
trace((t2:TestPoint));
// trace((t1:TestPoint)); // fails as expected: SomePoint2<{ y : Float, x : Float }> should be TestPoint
}
}
注意:我觉得这个解决方案可以很容易地改进(@:from 的实现是相同的),但是现在是凌晨 3 点,其他什么都没有想到。如果我最终弄清楚如何简化它,我会回来编辑它。