Flex判断数据类型的方法概述

来源:互联网 发布:编程圆的面积和周长 编辑:程序博客网 时间:2024/06/05 15:09

(一)通过反射机制来判断

 使用反射机制时,必须预先声明将要反射的类型,否则,反射时会爆出找不到这个类型的错误。因为FLEX中import声明的类是不会被编译进运行时环境的。如下

var temp:ComBox

 传进一个object,返回类的全名,然后判断

 

以下是基础数据类型和自定义类的输出。

com.rongzhong.vos.sepcialType::ComBox
int

Boolean
String
int

(二)通过FLEX本身的函数来判断数据类型。

主要有这么几种 as ,instanceof,is,typeof。

 

as:  计算第一个操作数指定的表达式是否是第二个操作数指定的数据类型的成员。

­如果第一个操作数是该数据类型的成员,则结果是第一个操作数。否则,结果是 null 值。

举例:public var myArray:Array = ["one", "two", "three"];
      trace(myArray as Array);  // one,two,three
   trace(myArray as Number); // null
   trace(myArray as int);    // null


 

instanceof:计算表达式的原型链中是否包含 function 的原型对象。

当与类一起使用时,instanceof 运算符与 is 运算符类似,这是因为类的原型链中包含它的所有超类。但是,原型链中不包含接口,因此当与接口一起使用时,instanceof 运算符的计算结果将始终为 false,而 is 运算符的计算结果将为 true(如果对象属于实现指定接口的类)。

举例:var mySprite:Sprite = new Sprite();
   trace(mySprite instanceof Sprite);        // true
   trace(mySprite instanceof DisplayObject); // true

 

is: 计算对象是否与特定的数据类型、类或接口兼容。注意也可以使用 is 运算符检查对象是否实现了某个接口。

举例:import flash.display.*;
   import flash.events.IEventDispatcher;

  var mySprite:Sprite = new Sprite();
  trace(mySprite is Sprite);           // true
  trace(mySprite is DisplayObject);    // true
  trace(mySprite is IEventDispatcher); // true

typeof:计算 expression,并返回指定表达式的数据类型的字符串。此结果仅限于六个可能的字符串值:booleanfunctionnumberobjectstringxml

举例:trace(typeof Array); // object
   trace(typeof Date);  // object
   trace(typeof 3);     // number
      var a:String = "sample";
   var b:String = new String("sample");
   trace(typeof a); // string
   trace(typeof b); // string