是否可以从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
{
-------------------------------
}
}
答案 0 :(得分: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];
}
}
答案 1 :(得分:0)
是的,您可以随时将所有值都粘贴到数组中,然后随机选择一个。
答案 2 :(得分: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))]);
}
}
}