Haxe抽象类

haxe中的抽象类是可以被实例化的,它更像一个已有类的包装,用于重载被包装类的赋值、取值、操作符等 例如:

//被包装类为Array<String> @:from对应的方法生成的结果赋值给该类的实例
abstract StringSplitter(Array<String>) {
    inline function new(a:Array<String>)
        this = a;
        
    @:from static public inline function fromString(s:String) {
        return new StringSplitter(s.split(""));
    }
}

//from to为 @:from 和 @:to 方法的替代简写,如果这样写,其中from与to之后的类型必须与被包装类型兼容
abstract MyInt(Int) from Int to Int {
    //@:op为操作符重载
    @:op(A + B) static public function add(lhs:MyInt, rhs:MyInt):MyInt;

    //@:commutative为反序有效,例如String*MyInt也能代入
    @:commutative @:op(A * B) static public function repeat(lhs:MyInt, rhs:String):String {
        var s:StringBuf = new StringBuf();
        for (i in 0...lhs)
            s.add(rhs);
        return s.toString();
    }
}
abstract MyReflect({}) from {} {
    //重载数组访问符,如xxx.[0]
    @:arrayAccess public inline function arrayAccess(key:String):Dynamic {
        return Reflect.field(this, key);
    }
    
    @:arrayAccess public inline function arrayWrite<T>(key:String, value:T):T {
        Reflect.setField(this, key, value);
        return value;
    }
}

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注