在我提出问题之前,这是我的代码结构的示例:
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();
如果您对我的问题有什么不明白的地方,请随时问我!