早上好
自从时间开始以来,人们一直希望并发明了在Flash AS3中进行枚举的方法。
许多尝试都存在各种问题,例如能否使用构造函数创建新类型的枚举(不安全)。
我相信以下在编译时是类型安全的,并且无法在运行时创建枚举类的新实例。
主要问题是AS3无法拥有私有构造函数。在这个例子中,构造函数只有在传递私有静态const变量ENFORCER时才能成功,该变量只在类内部可见。
package
{
public class PermissionsEnum
{
private static const ENFORCER = new Object();
public static const READ:PermissionsEnum = new PermissionsEnum(ENFORCER, 1);
public static const WRITE:PermissionsEnum = new PermissionsEnum(ENFORCER, 2);
public static const CREATE:PermissionsEnum = new PermissionsEnum(ENFORCER, 4);
public static const DELETE:PermissionsEnum = new PermissionsEnum(ENFORCER, 8);
private var _value:uint;
public function PermissionsEnum(e:Object, v:uint)
{
if (e != ENFORCER)
throw new Error("Attempted enum security breach.");
this._value = v;
}
public function get value() : uint
{
return this._value;
}
}
}
评论任何人?
其他先前的尝试允许某种循环引用(顺便提一下,Java编译器不允许,并且C#编译器允许)作为尝试禁止运行时创建更多枚举值。我认为这更美丽。
我们怎么想?
富
答案 0 :(得分:0)
您可以在构造函数中使用更严格的编译时限制(以下所有代码都在同一个PermissionsEnum.as
文件中):
package
{
public class PermissionsEnum
{
private static const ENFORCER:Enforcer = new Enforcer();
public static const READ:PermissionsEnum = new PermissionsEnum(ENFORCER, 1);
public static const WRITE:PermissionsEnum = new PermissionsEnum(ENFORCER, 2);
public static const CREATE:PermissionsEnum = new PermissionsEnum(ENFORCER, 4);
public static const DELETE:PermissionsEnum = new PermissionsEnum(ENFORCER, 8);
private var _value:uint;
public function PermissionsEnum(e:Enforcer, v:uint)
{
this._value = v;
}
public function get value() : uint
{
return this._value;
}
}
}
class Enforcer
{
}
答案 1 :(得分:0)
1)如何将值转换为枚举成员?
2)我在创建PermissionsEnum
时遇到一个问题:对其内部值没有共同控制。我的意思是,如果我在枚举中有5-10个成员,那么找到重复的值就没有问题了。但如果列表增长,那么在源代码中出错的机会也会消失:
public static const READ:PermissionsEnum = new PermissionsEnum(ENFORCER, 1);
public static const WRITE:PermissionsEnum = new PermissionsEnum(ENFORCER, 7);
public static const APPEND:PermissionsEnum = new PermissionsEnum(ENFORCER, 15);
public static const CREATE:PermissionsEnum = new PermissionsEnum(ENFORCER, 8);
public static const DELETE:PermissionsEnum = new PermissionsEnum(ENFORCER, 3);
public static const COMMIT:PermissionsEnum = new PermissionsEnum(ENFORCER, 6);
public static const SUBMIT:PermissionsEnum = new PermissionsEnum(ENFORCER, 21);
public static const POP:PermissionsEnum = new PermissionsEnum(ENFORCER, 22);
public static const PUSH:PermissionsEnum = new PermissionsEnum(ENFORCER, 3);
public static const SELECT:PermissionsEnum = new PermissionsEnum(ENFORCER, 17);
public static const DESELECT:PermissionsEnum = new PermissionsEnum(ENFORCER, 22);
public static const END:PermissionsEnum = new PermissionsEnum(ENFORCER, 15);