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."));
}

次のように、特定のアイテム クラスごとに use メソッドを呼び出すにはどうすればよいでしょうか。

World.Items[itemId].Use();

私の問題について何かわからないことがあれば、遠慮なく私に聞いてください!

4

1 に答える 1

4

ItemClass で Use Method を定義し、virtual としてマークします。次に、サブクラスでメソッドをオーバーライドとしてマークすると、必要なことを実行できるはずです

于 2012-06-09T21:37:27.227 に答える