2012-06-09 37 views
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."); 
    } 
} 

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

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

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

+0

这很好地工作。谢谢! –

+0

标记回答的问题。绿色复选框在左边.. :) –

+0

我要去:) StackOverflow需要我等几分钟才能接受它。 –