How to access a public array/vector from another class

孤街醉人 提交于 2019-12-08 10:39:53

问题


I have a vector in my Main class file that store objects. I will like to be able to add more objects to that SAME vector from a different class. I gave the vector in my main class the "public" modifier. I now need the syntax to reference it in my other class file

public var badChar:Vector.;


回答1:


You have options. How you approach it is dependent on your project setup, and the needs of the property. Is it an instantiated object, or should there ever only be one (even if the class is instantiated multiple times)? Do you need direct access to it regardless of any relationship to the stage? Each solution below has pros and cons.


Class-to-Class via Stage

Assuming the following main foo.as class:

package {
    public class Foo {
        public var bool:Boolean = true;
    }
}

Bar class:

package {
    public class Bar extends Sprite {
        import flash.events.Event;

        public function Bar() {
            addEventListener(Event.ADDED_TO_STAGE, accessFoo);
        }

        private function accessFoo(e:Event):void {
            trace(this.parent["f"].bool); // traces "true"
        }
    }
}

Document Code:

var f:Foo = new Foo();
var b:Bar = new Bar();
addChild(b);

Inheritance

Foo Class:

package {
    public class Foo {
        public var bool:Boolean = true;
    }
}

Bar Class

package {
    public class Bar extends Foo {
        public function Bar() {
            trace(bool); // traces "true"
        }
    }
}

Class-to-Class via Static

Some disclaimers should be in order for Static properties, but I'll leave you to read up on those.

Foo Class:

package {
    public class Foo {
        public static var bool:Boolean = true;
    }
}

Bar Class

package {
    public class Bar {
        public function Bar() {
            trace(Foo.bool); // traces "true"
        }
    }
}

Direct Access via New Declaration

Foo Class:

package {
    public class Foo {
        public var bool:Boolean = true;
    }
}

Bar Class

package {
    public class Bar {
        import Foo;

        public function Bar() {
            trace(new Foo().bool); // traces "true"
        }
    }
}

Access via Sharing

Foo Class:

package {
    public class Foo {
        public var bool:Boolean = true;
    }
}

Bar Class

package {
    public class Bar {
        import Foo;
        public var fluffy:Foo;

        public function Bar() {
            trace(fluffy.bool);
        }
    }
}

Document Code:

var f:Foo = new Foo();
var b:Bar = new Bar();
b.fluffy = f;

Note that after the third line in the document code, fluffy is no longer an undeclared variable and will now point to the f object, where the properties updated in it (such as bool) will reflect inside of Bar.



来源:https://stackoverflow.com/questions/21920209/how-to-access-a-public-array-vector-from-another-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!