haxe:如何在泛型 class 中使用具体枚举类型的枚举值?

haxe: How to use enum values of concrete enum type in generic class?

我想制作适用于传递的枚举类型的通用 class,如下所示:

class Holder<E, T> { // I suppose to pass only enum types as E, how to limit them?

    function new() {
        mMap = new Map<EnumValue, T>();
    }

    function add(aKey:EnumValue, aValue:T) { // aKey is practically ANY enum value
        mMap.set(aKey, aValue);
    }

    var mMap:Map<EnumValue, T>; // what type should I use as key? like E<EnumValue>

}

enum Keys {
    A;
    B;
}

enum Injection {
    NOT_ALLOWED;
}

// first drawback
var holder = new Holder<Keys, String>();
holder.add(Keys.A, "This is A");
holder.add(Keys.B, "This is B");
holder.add(Injection.NOT_ALLOWED, "Not allowed by design!"); // it must not be allowed

// second drawback
var strange = new Holder<String, String>(); // it must not be allowed too

我从不在 class 声明中使用 E 类型,因为我不明白如何将枚举值传播回它的类型。而且我不能只在 class 定义中编写 Holder<Enum<E>,T> 来使用 E 类型作为枚举值。 我应该怎么做才能像枚举类型一样限制 E 然后只获取这种类型的参数?

您只需在 E 上指定一个约束,即 E:EnumValue,并将 aKey 的类型更改为 Eadd 函数

完整代码:

package;

class Main {

    public static function main()
    {
        // first drawback
        var holder = new Holder<Keys, String>();
        holder.add(Keys.A, "This is A");
        holder.add(Keys.B, "This is B");
        holder.add(Injection.NOT_ALLOWED, "Not allowed by design!"); // compiler error: Injection should be Keys

        // second drawback
        var strange = new Holder<String, String>(); // compiler error: String should be EnumValue
    }
}

class Holder<E:EnumValue, T> { // constrain the type parameter "E" to be an "EnumValue"

    public function new() {
        mMap = new Map(); // actually you don't have to specify the type parameters when constructing the object
    }

    public function add(aKey:E, aValue:T) { // aKey is simply of type "E"
        mMap.set(aKey, aValue);
    }

    var mMap:Map<E, T>; 

}

enum Keys {
    A;
    B;
}

enum Injection {
    NOT_ALLOWED;
}