【问题标题】:Creating read-only properties in Actionscript 3在 Actionscript 3 中创建只读属性
【发布时间】:2010-11-24 05:24:30
【问题描述】:

AS3 中的许多库类都具有“只读”属性。是否可以在自定义 as3 类中创建此类属性?换句话说,我想创建一个具有公共读取但私有集的属性,而不必为我想要公开的每个属性创建一个复杂的 getter/setter 系统。

【问题讨论】:

    标签: actionscript-3 properties readonly


    【解决方案1】:

    只读的唯一方法是使用 AS3 的内置 getset 函数。

    编辑:原始代码是只写的。对于只读,只需使用 get 而不是 set,如下所示:

    package
    {
    
    import flash.display.Sprite;
    
    public class TestClass extends Sprite
    {
        private var _foo:int = 5;
    
        public function TestClass() {}
    
        public function get foo():int{ return _foo; }
        public function incrementFoo():void { _foo++; }
    }
    
    }
    

    这允许您像这样访问 foo:

    var tc:TestClass = new TestClass();
    trace(tc.foo);
    
    tc.incrementFoo();
    trace(tc.foo);
    

    以下是原文,仅供参考:

    package
    {
    
    import flash.display.Sprite;
    
    public class TestClass extends Sprite
    {
        private var _foo:int;
    
        public function TestClass() {}
    
        public function set foo(val:int):void{ _foo = val; }
    }
    
    }
    

    这将允许您像这样在外部设置 _foo 的值:

    var tc:TestClass = new TestClass();
    tc.foo = 5;
    
    // both of these will fail
    tc._foo = 6;
    var test:int = tc.foo;
    

    【讨论】:

      【解决方案2】:

      您不能拥有同名的公共集和私人获取。但正如 James 所展示的,您可以将 setter 重命名为其他名称,并将其设为私有以获取只读属性。

      【讨论】:

        【解决方案3】:

        你不能这样吗?

        package
        {
        
        import flash.display.Sprite;
        
        public class TestClass extends Sprite
        {
            private var _foo:int = 5;
        
            public function TestClass() {}
        
            public function get foo():int{ return _foo; }
            public function set foo(value:int):void{ throw new Error("The variable foo is read-only"); }
        }
        
        }
        

        【讨论】:

          【解决方案4】:

          更简单的是,只需定义“getter”(公共函数 get),而不是“setter”(公共函数集)。这样,如果有人试图写入该属性,Flash 将抛出错误。如上所述,无需手动抛出任何错误。

          【讨论】:

            猜你喜欢
            • 2021-10-04
            • 1970-01-01
            • 2021-05-27
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2010-11-10
            • 1970-01-01
            • 2017-06-06
            相关资源
            最近更新 更多