我正在制作这个游戏,但我遇到了结构问题。我创建了一个名为Structure的类,其他类如Traps,Shelter,Fireplace继承自此类。游戏中的图块有自己的类(Tile),并且在该图块上有结构列表。我可以成功地在列表中包含的tile上构建结构。当我尝试从Traps等类中访问函数时,问题就出现了。它不起作用。我只能使用基类Structure中的函数。
Tile中的列表:
class Tile
{
public List<Structure> Structures = new List<Structure>();
}
我如何建造陷阱或其他建筑物:
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;
}
}
当我绘制结构时(这是我的问题所在,请注意注释)
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);
}
}
Soo ......我想知道如何访问我不想使用的功能?
答案 0 :(得分:6)
向基类添加虚拟方法;
public class Structure
{
public virtual void ColorBody(Graphics g, int someParam1, int someParam2)
{
// do nothing in the base class
}
}
并覆盖FireBody中的方法
public class FireBody : Structure
{
public override void ColorBody(Graphics g, int someParam1, int someParam2)
{
// do something here for FireBody
}
}
如果所有继承自Structure
的类都需要它,那么将其作为抽象;
public abstract class Structure
{
public abstract void ColorBody(Graphics g, int someParam1, int someParam2);
}
答案 1 :(得分:4)
在计算机上,s
仅一个Structure
。如果要调用只有Fireplace
类但具有抽象类Structure
没有的特定方法(例如Fireplace
类可能有BurnWood()
方法,那就不会对于Structure
有意义,然后你想让计算机知道这个Structure
实际上也一个Fireplace
(例如)。所以你可以通过铸造来做到这一点;例如:
((Fireplace)s).ColorBody(g, x - minx, y - miny);
或
(s as Fireplace).ColorBody(g, x - minx, y - miny);
有关投射和使用as
运算符之间的区别,请参阅this post。
答案 2 :(得分:1)
我可以从你的问题中注意到你在两个类中有两个重载函数,即对于基类和派生类,你有不同的数字函数参数
在这种情况下,您必须支持compile type polymophism,如下所示
public BaseQueryClass
{
public string QueryClassFunc(string mystring, int i)
{
return mystring + i.ToString();
}
}
public QueryClassDerived : BaseQueryClass
{
public string QueryClassFunc(string mystring)
{
return mystring;
}
}
您可以调用您的方法,如下所示
BaseQueryClass qClass = new BaseQueryClass();
qClass.QueryClassFunc("mystring", 1);
((QueryClassDerived)qClass).QueryClassFunc("test");
希望我在这里没有遗漏任何东西