Haxe:匹配接口的函数参数

Haxe: Function argument that matches an interface

我有一个方法(在 Haxe 中)需要接受任何具有 'width' 和 'height' 属性 的对象。我假设我可以通过接口以某种方式做到这一点,但出于我的目的,传入的对象不需要实现接口,它只需要是 any 对象宽度和高度 属性.

这不行,因为你传入的对象需要实现接口:

Interface IWidthAndHeight{
    public var width : Float;
    public var height : Float;
}

Class Main{

    var o : IWidthAndHeight;

    public function setObject( o : IWidthAndHeight ){
        this.o = o;
    }

}

目前我正在使用 Dynamic,并手动检查属性是否存在,但有没有更聪明的方法?当前方法:

Class Main{

    var o : Dynamic;

    public function setObject( o : Dynamic ){
        if (propertiesExist(o,['width','height'])){
            this.o = o;
        }
    }

    // Note: propertiesExist is my own method. Just assume it works :)
}

感谢任何帮助。谢谢!

你可以在这里使用anonymous structures

typedef WidthAndHeight = {
    width:Float,
    height:Float
}
class Main {
    var o:WidthAndHeight;
    public function setObject(o:WidthAndHeight) {
        this.o = o;
    }
}

这只是 var o:{width:Float, height:Float};typedef 的替代方法。 setObject 参数中的任何 class 或结构将在编译时检查这些字段,这称为 structural subtyping.