Flash AS3:访问非';t在超级班
如果我有三门课:Flash AS3:访问非';t在超级班,flash,actionscript-3,flash-builder,flashdevelop,Flash,Actionscript 3,Flash Builder,Flashdevelop,如果我有三门课: 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 ExtendedE
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 () {
}
}
您可以看到,最后两个类扩展了第一个类,并且都具有“variable”属性。如果我有一个Example实例,并且我确信它也是一个ExtendedExample或一个ExtendedExample实例,那么是否有某种方法可以访问“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块中访问该属性。我建议在逻辑更容易遵循的地方使用上面提到的类型转换
如果变量在所有子类中都使用,只需在父类中定义它,并在每个子类中为其指定一个特定值。@Lucas按照下面的代码更改代码
function functionThatReceivesAnExtendedExample (ex:Example):void {
if(ex is ExtendedExample) {
(ex as ExtendedExample).func()
} else if(ex is AnotherExtendedExample)
{
(ex as AnotherExtendedExample).funct()
}
}
希望这将有所帮助正如RIAstar在他的评论中所说,最明显的方法是使
示例
也有一个函数
并在子类中重写它
实现一个接口,而不是扩展一个基类,或者两者兼而有之,这可能是另一种方式,可以让函数在ex
上调用func
,而不考虑ex
对象的确切类,并且没有示例
类必须实现func
函数,如您的示例所示。类似于这样,在示例代码的基础上:
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”类。不会解决我的问题,因为我处理的不是var,而是函数。我只是想让你明白我的问题,我假设funct上的t是一个拼写错误。答案几乎相同:将“func”移动到“Example”并在子类中重写它。是的,这就是答案,重写,谢谢!我正在用这个答案为我自己的问题写一个答案,这样其他人就可以很容易地找到它。你想自己做吗?这样我就可以选择你的答案了?因为你把问题换成了处理函数,所以我的例子仍然有效,但是你需要重写父函数并为每个扩展类定义它。强制转换方法的工作原理与前面描述的一样。我无法访问它,因为我没有处理动态对象,而且我也避免使用它们,因为它们速度较慢