2012-01-29 39 views
0

如果我有三類: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() 
    } 

} 
+1

將'variable'移動到'Example'類。 – RIAstar 2012-01-29 15:11:35

+0

不會解決我的問題,因爲我沒有處理var,但有一個函數。我只是編輯了我的問題,以便你明白 – Lucas 2012-01-29 15:52:16

+0

我假設'功能'上的't'是一個錯字。答案几乎與之相同:將'func'移動到'Example'並在子類中覆蓋它。 – RIAstar 2012-01-29 16:52:25

回答

1

如果變量在你的一些子類中被使用,但不是在所有的人,你有沒有在父類中定義它,你仍然可以嘗試訪問它。我建議一些快速鑄造:

if (ex is AnotherExtenedExample || ex is ExtendedExample) 
{ 
    var tmpex:ExtendedExample = ex as ExtendedExample; 
    trace (tmpex.variable); 
} 

你也可以將它轉換爲動態對象類型,並嘗試訪問在try..catch塊的屬性。我建議使用像上面那樣的邏輯更容易遵循的鑄造。

如果變量用於所有子類,只需在父類中定義它並在每個子類中爲其指定一個特定值即可。

+0

由於您將問題轉換爲處理函數,因此我的示例仍然有效,但您需要覆蓋父函數併爲每個擴展類定義它。鑄造方法的工作原理與上述相同。 – 2012-01-29 16:05:29

+0

我無法訪問它,因爲我沒有處理動態對象,而且我也避免使用它們,因爲它們比較慢 – Lucas 2012-01-29 16:44:16

1

@Lucas改變你的代碼如下代碼

function functionThatReceivesAnExtendedExample (ex:Example):void { 
    if(ex is ExtendedExample) { 
     (ex as ExtendedExample).func() 
    } else if(ex is AnotherExtendedExample) 
    { 
     (ex as AnotherExtendedExample).funct() 
    } 
} 

希望這將有助於

0

由於RIAstar在他的評論說,最明顯的方法是使Example也有func功能,在子類中覆蓋它。

實現一個接口,而不是延伸的基類,或者做兩個,可能是另一種方法,讓上exfunctionThatReceivesAnExtendedExample通話func而不在乎ex對象是什麼確切類,而不必實施funcExample類函數,如你的例子。因此,以您的示例代碼爲基礎:

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() 
}