VB.NET声明为Object后调用类函数

时间:2012-05-04 05:28:40

标签: vb.net class generics object

我想知道是否有办法做到这一点......我正在使用vs2010和WP7 SDK。 (VB.NET)

我在全球范围内宣布这一点。

public objGame as object

然后说我有课程:Game1Game2

为了示例,我们只是说两个类都有一个Update()函数

我想设置objGame = Game1(或Game2)

然后可以致电objGame.Update()

有办法做到这一点吗?

3 个答案:

答案 0 :(得分:3)

使用方法Update()声明接口IGame。从它继承Game1和Game2。

IGame objGame= Game1() [or Game2]

objGame.Update()

这里有关于OOP中多态性的维基link

答案 1 :(得分:1)

您可以使用反射来获取类对象的类型,然后在将其转换为特定类之后调用update方法。

C#中的代码片段,可能是您会理解该怎么做。这里是Shared类中的object,并将对象设置为您的类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();`

希望这能帮到你..

答案 2 :(得分:-1)

首先将您的公共对象声明为Game1或Game2

Public objGame As New Game1

然后,无论你对象做什么,实际上代表Game1或Game2

objGame.Update()