2012-05-04 15 views
1

我想看看是否有辦法做到這一點...我使用vs2010與WP7 SDK。 (VB.NET)VB.NET聲明爲對象後調用類功能

我在全球範圍內聲明這一點。

public objGame as object

然後說,我有類:Game1Game2

的例子起見,我們只能說這兩個類有一個Update()功能

我想設置objGame = Game1(或Game2)

然後能打電話給objGame.Update()

有沒有辦法做到這一點?

回答

3

用方法Update()聲明一個接口IGame。從它繼承Game1和Game2。

IGame objGame= Game1() [or Game2] 

objGame.Update() 

這是關於OOP中的多態性的wiki link

+0

+1正確的信息和suggestion..but運是有點關於提取分配類對象的引用類型... –

-1

首先聲明你的公共對象要麼的Game1或GAME2

Public objGame As New Game1 

那麼無論你的目標做的實際上是代表兩種的Game1或GAME2

objGame.Update() 
1

您可以使用反射來獲取類型的類對象,然後在將其轉換爲特定的類之後調用更新方法。

在C#中的代碼片段,可能你會明白該怎麼做。這裏的object在Shared類中,並將對象設置爲您的類Game1或Game2。然後訪問然後使用小反射來處理對象的運行時間。

public static class GameCommon 
    { 
     public static object currentGame; 
    } 

///使用.GetType()

GameCommon.currentGame = new Game1(); 

      if (GameCommon.currentGame != null) 
      { 
       Type type = GameCommon.currentGame.GetType(); 
       if (type.Name == "Game1") 
       { 
        ((Game1)GameCommon.currentGame).Update();  
       } 
       else if (type.Name == "Game2") 
       { 
        ((Game2)GameCommon.currentGame).Update();  
       } 
      }` 

的另一個最好的辦法是Interface多態性與恕我直言,這是實現正確的方式..

檢查:

public static class GameCommon 
    { 
     public static IGame currentGame; 
    } 

    public interface IGame 
    { 
     void Update(); 
    } 
    public class Game1 : IGame 
    { 
     public void Update() 
     { 
      Console.WriteLine("Running:Game1 Updated"); 
     } 
    } 

    public class Game2 : IGame 
    { 
     public void Update() 
     { 
      Console.WriteLine("Running:Game2 Updated"); 
     } 
    }` 

叫做:

GameCommon.currentGame = new Game1(); 

      if (GameCommon.currentGame != null) 
      { 
       GameCommon.currentGame.Update(); 
      } 

      GameCommon.currentGame = new Game2(); 
      GameCommon.currentGame.Update(); 
      Console.ReadKey();` 

希望這有助於你..