The*_*978 3 constants actionscript-3
我想抛出一个参数错误,如果一个特定的函数在没有传递值的情况下不起作用,该值也恰好是包含该函数的类的公共常量.
无论如何要确定一个类是否拥有一个公共常量而不是必须通过所有这些来迭代?
这样的事情:
public static const HALIFAX:String = "halifax";
public static const MONTREAL:String = "montreal";
public static const TORONTO:String = "toronto";
private var cityProperty:String;
public function set city(value:String):void
{
if (!this.hasConstant(value))
throw new ArgumentError("set city value is not applicable.");
cityProperty = value;
}
public function get city():Strig
{
return cityProperty;
}
Run Code Online (Sandbox Code Playgroud)
目前,对于这个功能,我必须编写像这样的城市设定函数:
public function set city(value:String):void
{
if (value != HALIFAX && value != MONTREAL && value != TORONTO)
throw new ArgumentError("set city value is not applicable.");
cityProperty = value;
}
Run Code Online (Sandbox Code Playgroud)
这是完成这项任务的唯一方法吗?
是的,如果您使用反射:
private var type:Class;
private var description:XML;
private function hasConstant (str : String ) : Boolean
{
if (description == null)
{
type = getDefinitionByName (getQualifiedClassName (this)) as Class;
description = describeType (type);
}
for each ( var constant:XML in description.constant)
{
if (type[constant.@name] == str) return true;
}
return false;
}
Run Code Online (Sandbox Code Playgroud)
请注意,为此,所有常量必须始终是声明的String对象public static const.
| 归档时间: |
|
| 查看次数: |
1303 次 |
| 最近记录: |