从基类对象列表中调用子类'方法?

时间:2012-06-09 21:33:07

标签: c# list class-hierarchy

在我提出问题之前,以下是我的代码结构示例:

abstract class Entity
{
    #region Declarations
    public string Name;
    public string Description;
    #endregion

    #region Constructor
    public Entity(string Name, string Description)
    {
        this.Name = Name;
        this.Description = Description;
    }
    #endregion
}

abstract class Item : Entity
{
    #region Declarations
    public bool SingleUse;
    #endregion

    #region Constructor
    public Item(string Name, string Description, bool SingleUse = false)
        :base(Name, Description)
    {
        this.SingleUse = SingleUse;
    }
    #endregion

    #region Public Methods
    public void NoUse()
    {
        Program.SetError("There is a time and place for everything, but this is not the place to use that!");
    }
    #endregion
}

class BrassKey : Item
{
    public BrassKey(string Name, string Description, bool SingleUse = false)
        :base(Name, Description, SingleUse)
    {
    }

    public void Use()
    {
        if (Player.Location == 2)
        {
            Program.SetNotification("The key opened the lock!");
            World.Map[2].Exits.Add(3);
        }
        else
        {
            NoUse();
            return;
        }
    }
}

class ShinyStone : Item
{
    public ShinyStone(string Name, string Description, bool SingleUse = false)
        : base(Name, Description, SingleUse)
    {
    }

    public void Use()
    {
        if (Player.Location == 4)
        {
            Player.Health += Math.Min(Player.MaxHealth / 10, Player.MaxHealth - Player.Health);
            Program.SetNotification("The magical stone restored your health by 10%!");
        }
        else
        {
            Program.SetNotification("The shiny orb glowed shiny colors!");
        }
    }
}

class Rock : Item
{
    public Rock(string Name, string Description, bool SingleUse = false)
        : base(Name, Description, SingleUse)
    {
    }

    public void Use()
    {
        Program.SetNotification("You threw the rock at a wall. Nothing happened.");
    }
}

然后我在Item类中构建了World个对象的列表。列表中的每个对象都是它的项目类型。

public static List<Item> Items = new List<Item>();

private static void GenerateItems()
{
    Items.Add(new BrassKey(
        "Brass Key",
        "Just your generic key thats in almost every game.",
        true));

    Items.Add(new ShinyStone(
        "Shiny Stone",
        "Its a stone, and its shiny, what more could you ask for?"));

    Items.Add(new Rock(
        "Rock",
        "It doesn't do anything, however, it is said that the mystical game designer used this for testing."));
}

我怎么能像这样调用每个特定项目类的使用方法:

World.Items[itemId].Use();

如果您对我的问题有所了解,请不要犹豫,问我!

1 个答案:

答案 0 :(得分:4)

在ItemClass中定义Use Method并将其标记为虚拟。然后在您的子类中将该方法标记为覆盖,您应该能够执行您想要的操作