我正在制作这个游戏,但我遇到了结构问题.我创建了一个名为Structure的类,其他类如Traps,Shelter,Fireplace继承自此类.游戏中的图块有自己的类(Tile),并且在该图块上有结构列表.我可以成功地在列表中包含的tile上构建结构.当我尝试从Traps等类中访问函数时,问题就出现了.它不起作用.我只能使用基类Structure中的函数.
列表中的列表:
class Tile
{
public List<Structure> Structures = new List<Structure>();
}
Run Code Online (Sandbox Code Playgroud)
我如何建造陷阱或其他建筑物:
bool anyFireplace = Bundle.map.tile[Bundle.player.X, Bundle.player.Y].Structures.OfType<Shelter>().Any();
if (!anyFireplace)
{
woodlogsCost = 4;
if (Bundle.player.Woodlogs - woodlogsCost >= 0)
{
Bundle.map.tile[Bundle.player.X, Bundle.player.Y].Structures.Add(new Shelter(Bundle.player.X, Bundle.player.Y));
Bundle.player.Woodlogs -= woodlogsCost;
}
}
Run Code Online (Sandbox Code Playgroud)
当我绘制结构时(这是我的问题所在,请注意注释)
foreach (Structure s in Bundle.map.tile[x, y].Structures)
{
if (s is Fireplace)
{
//This is the function from base class Strucure
s.ColorBody(g, 10, x - minx, y - miny, 0, Brushes.Firebrick);
// The function that I wan´t to use but can´t be used
//s.ColorBody(g, x - minx, y - miny);
}
if (s is Shelter)
{
s.ColorBody(g, 10, x - minx, y - miny, 1, Brushes.ForestGreen);
}
if (s is Sleepingplace)
{
s.ColorBody(g, 10, x - minx, y - miny, 2, Brushes.Brown);
}
if (s is Trap)
{
s.ColorBody(g, 10, x - minx, y - miny, 3, Brushes.Silver);
}
if (s is Barricade)
{
s.ColorBody(g, 10, x - minx, y - miny, 4, Brushes.DarkOliveGreen);
}
}
Run Code Online (Sandbox Code Playgroud)
所以...我想知道如何访问我不想使用的功能?
向基类添加虚方法;
public class Structure
{
public virtual void ColorBody(Graphics g, int someParam1, int someParam2)
{
// do nothing in the base class
}
}
Run Code Online (Sandbox Code Playgroud)
并覆盖FireBody中的方法
public class FireBody : Structure
{
public override void ColorBody(Graphics g, int someParam1, int someParam2)
{
// do something here for FireBody
}
}
Run Code Online (Sandbox Code Playgroud)
如果所有继承自的类都Structure需要它,那么就把它变成抽象的;
public abstract class Structure
{
public abstract void ColorBody(Graphics g, int someParam1, int someParam2);
}
Run Code Online (Sandbox Code Playgroud)