1

是否可以从 AS3 中的类中获取随机常数?

class Constat
{
    public static const constA:String = "const1";
    public static const constB:String = "const2";
    ...

    /** this method must return a random constant */
    public static function getRandomConst():String
    {
         -------------------------------
    }
}
4

3 回答 3

2

您可以使用describeType()收集类中定义的所有常量,然后从那里随机选择一个。

public class Constat
{

    public static const constA:String = "const1";
    public static const constB:String = "const2";

    private static var _constants:Vector.<String>;


    public static function getRandomConst():String
    {
        if(_constants === null)
        {
            _constants = new <String>[];

            var def:XML = describeType(Constat);

            for each(var i:XML in def.constant)
            {
                _constants.push(i.@name);
            }
        }


        // Select random.
        var con:String = _constants[ int(Math.random() * _constants.length) ];

        return Constat[con];
    }

}
于 2013-03-04T02:58:09.567 回答
0

是的,您总是可以将所有值粘贴到一个数组中并随机选择一个。

于 2013-03-03T08:42:00.300 回答
0

设置为 const 名称后跟一个数字。并使用带有Math.random().

试试这个

package {

    import flash.display.Sprite;

    public class MyClass extends Sprite
    {
        public static const constA:String = "00";
        public static const constB:String = "11";
        public static const constC:String = "22";
        public static const constD:String = "33";
        public static const constE:String = "44";
        public static const constF:String = "55";
        public static const constG:String = "66";
        public static const constH:String = "77";
        public static const constI:String = "88";
        public static const constJ:String = "99";
                             .
                             .
                             .

        public function MyClass() 
        {   
            MyClass.test();
        }

        public static function mapped(i:int):String
        {
            //65 is A
            return String.fromCharCode(65+i);                   
        }

        public static function test():void
        {
            trace(MyClass["const"+mapped(int(Math.random()*10))]);
        }

    }
}
于 2013-03-03T11:31:45.343 回答