【问题标题】:haxe: How to use enum values of concrete enum type in generic class?haxe:如何在泛型类中使用具体枚举类型的枚举值?
【发布时间】:2015-11-18 11:22:37
【问题描述】:

我想创建一个与传递的枚举类型一起使用的泛型类,如下所示:

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

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

【问题讨论】:

    标签: generics types enums haxe


    【解决方案1】:

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

    完整代码:

    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;
    }
    

    【讨论】:

    • 谢谢!看起来很简单,但我还没迈出最后一步。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-18
    • 1970-01-01
    • 2017-02-03
    相关资源
    最近更新 更多