0

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

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

如果您对我的问题有什么不明白的地方,请随时问我!

4

1 回答 1

4

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

于 2012-06-09T21:37:27.227 回答