AS3:访问对象属性或扩展分类功能,是不是在超类
如果我有三类:AS3:访问对象属性或扩展分类功能,是不是在超类
public class Example {
public function Example() {
}
}
public class ExtendedExample extends Example {
public function func():void {
//here is what this class does different that the next
}
public function ExtendedExample() {
}
}
public class AnotherExtendedExample extends Example {
public function funct():void {
//here is what this class does, and it is differente from ExtendedExample
}
public function AnotherExtendedExample() {
}
}
你可以看到,最后两个类扩展了第一个,并且都'可变'属性。如果我有一个Example的实例,并且我确定它也是一个ExtendedExample或AnotherExtendedExample实例,是否有某种方法可以访问'variable'属性?喜欢的东西
function functionThatReceivesAnExtendedExample (ex:Example):void {
if(some condition that I may need) {
ex.func()
}
}
如果变量在你的一些子类中被使用,但不是在所有的人,你有没有在父类中定义它,你仍然可以尝试访问它。我建议一些快速铸造:
if (ex is AnotherExtenedExample || ex is ExtendedExample)
{
var tmpex:ExtendedExample = ex as ExtendedExample;
trace (tmpex.variable);
}
你也可以将它转换为动态对象类型,并尝试访问在try..catch块的属性。我建议使用像上面那样的逻辑更容易遵循的铸造。
如果变量用于所有子类,只需在父类中定义它并在每个子类中为其指定一个特定值即可。
由于您将问题转换为处理函数,因此我的示例仍然有效,但您需要覆盖父函数并为每个扩展类定义它。铸造方法的工作原理与上述相同。 – 2012-01-29 16:05:29
我无法访问它,因为我没有处理动态对象,而且我也避免使用它们,因为它们比较慢 – Lucas 2012-01-29 16:44:16
@Lucas改变你的代码如下代码
function functionThatReceivesAnExtendedExample (ex:Example):void {
if(ex is ExtendedExample) {
(ex as ExtendedExample).func()
} else if(ex is AnotherExtendedExample)
{
(ex as AnotherExtendedExample).funct()
}
}
希望这将有助于
由于RIAstar在他的评论说,最明显的方法是使Example
也有func
功能,在子类中覆盖它。
实现一个接口,而不是延伸的基类,或者做两个,可能是另一种方法,让上ex
functionThatReceivesAnExtendedExample
通话func
而不在乎ex
对象是什么确切类,而不必实施func
的Example
类函数,如你的例子。因此,以您的示例代码为基础:
public class Example {
public function Example() {
}
}
public interface IFunc {
function func():void;
}
public class ExtendedExample extends Example implements IFunc {
public function func():void {
//here is what this class does different that the next
}
}
public class AnotherExtendedExample extends Example implements IFunc {
public function func():void {
//here is what this class does, and it is differente from ExtendedExample
}
}
function functionThatReceivesAnExtendedExample (ex:IFunc):void {
ex.func()
}
将'variable'移动到'Example'类。 – RIAstar 2012-01-29 15:11:35
不会解决我的问题,因为我没有处理var,但有一个函数。我只是编辑了我的问题,以便你明白 – Lucas 2012-01-29 15:52:16
我假设'功能'上的't'是一个错字。答案几乎与之相同:将'func'移动到'Example'并在子类中覆盖它。 – RIAstar 2012-01-29 16:52:25