Dynamic Class & Sealed Class

从是否能够动态的添加实例属性或方法,能够将类分为动态类(Dynamic Class)和密封类(Sealed Class)。动态类生成的实例能够在运行时动态添加属性,而密封类则不能够。所谓的动态的非动态的区分仅存在于编译阶段。for..in 与for each ... in只能遍历 动态类的动态属性(运行如下例子能够查看效果)
package com.test
{
   public    dynamic class DynamicClassExample
  {
    
     public function DynamicClassExample()
    {
    }
    
     private var _name:String;
     private var _age: int;
     public var test:String = "test";
    
     public function set name(val:String): void
    {
       this._name = val;
    }
     public function get name():String
    {
       return this._name;
    }
    
     public function set age(val: int): void
    {
       this._age = val;
    }
     public function get age(): int
    {
       return this._age;
    }
  }
}
package com.test
{
   public class SealedClassExample
  {
    
     public function SealedClassExample()
    {
    }
    
     private var _name:String;
     private var _age: int;
     public var test:String = "test";
     public function set name(val:String): void
    {
       this._name = val;
    }
     public function get name():String
    {
       return this._name;
    }
    
     public function set age(val: int): void
    {
       this._age = val;
    }
     public function get age(): int
    {
       return this._age;
    }
  }
}
<?xml version= "1.0" encoding= "utf-8"?>
<mx:Application xmlns:mx= "http://www.adobe.com/2006/mxml" layout="absolute" horizontalAlign="center" verticalAlign="middle">
  <mx:Script>
    <![CDATA[
      import com.test.SealedClassExample;
      import com.test.DynamicClassExample;
      private function testDynamic():void
      {
        var dy:DynamicClassExample = new DynamicClassExample();
        dy.age = 10;
        dy.name = "Dynamic"
        dy.newAddProp = "Hello,Dynamic class!";
        dy.url = "com.test.Dynamic.url";
        for( var k in dy)
        {
          tad.text +=k+":"+dy[k]+"\n";
        }
        
      }
      private function testSealed():void
      {
        var seal:SealedClassExample = new SealedClassExample();
        seal.age = 10;
        seal.name = "seal";
        //seal.newAddProp = "You had better not do that!";
        //seal.url = "com.test.sealed.url";
        // if the below code is not commented,the compiler will indicate the error:access undefined property.
        for( var k in seal)
        {
          tas.text +=k+":"+seal[k]+"\n";
        }
      }
    ]]>
  </mx:Script>
  <mx:HDividedBox width="100%" height="100%" horizontalAlign="left" verticalAlign="top">
    <mx:VBox width="50%" height="100%">
      <mx:Button label="testDynamic" click="testDynamic()"/>
      <mx:TextArea text="" id="tad" width="379" height="460"/>
    </mx:VBox>
    <mx:VBox width="50%" height="100%">
      <mx:Button label="testSealed" click="testSealed()"/>
      <mx:TextArea text="" id="tas" width="329" height="470"/>     </mx:VBox>   </mx:HDividedBox>     </mx:Application>
相关文章
相关标签/搜索