2014-08-31 65 views
-2

是否可以創建一個表示許多類對象的變量並調用該類中存在的函數? 我要創建這樣的事情..創建一個變量以適應所有類的類型

class A{ 
    void DoSomething(){ 
     //some code 
    } 
} 

class B{ 
    void DoSomething(){ 
     //some code 
    } 
} 

class Controller{ 
    public ClassType theObject; 
    public void DoSomething(){ 
     theObject.DoSomething(); 
    } 
} 

class Main{ 
    public static void main(){ 
     A objectA = new A(); 
     B objectB = new B(); 
     Controller objectC = new Controller(); 

     objectC.theObject = objectA; 
     objectC.DoSomething(); 

     objectC.theObject = objectB; 
     objectC.DoSomething(); 
    } 
} 

有沒有人知道如何做到這一點(什麼關鍵字來改變類ControllerClassType),或者我需要使用搜索這樣的關鍵詞是什麼?

+3

你在找接口嗎? – 2014-08-31 11:44:54

回答

3

您可以創建一個Interface,讓這兩個類A和B實現它。

interface ICanDoSomething { 
    void DoSomething(); 
} 

class A : ICanDoSomething { 
    void DoSomething(){ 
     //some code 
    } 
} 

class B : ICanDoSomething{ 
    void DoSomething(){ 
     //some code 
    } 
} 

class Controller { 
    public ICanDoSomething theObject; 
    public void DoSomething(){ 
     theObject.DoSomething(); 
    } 
} 

.... 
0

我試着保持答案儘可能類似於您的代碼。你所看到的稱爲接口。作爲一個非常基本的解釋,實現接口的類需要爲接口中定義的每個方法提供代碼。因此,通過多態性,您可以將具體類的實例(如AB)分配給ClassType,這是您的接口。然後可以調用當前分配的對象的接口中定義的任何方法。

interface ClassType 
{ 
    void DoSomething(); 
} 

class A : ClassType 
{ 
    void DoSomething() 
    { 
     //some code 
    } 
} 

class B : ClassType 
{ 
    void DoSomething() 
    { 
     //some code 
    } 
} 

class Main 
{ 
    public static void main() 
    { 
     A objectA = new A(); 
     B objectB = new B(); 
     ClassType objectC; 

     objectC = objectA; 
     objectC.DoSomething(); 

     objectC = objectB; 
     objectC.DoSomething(); 
    } 
}