3

我正在制作这个游戏,但我遇到了结构问题。我创建了一个名为 Structure 的类,其他类如 Traps、Shelter、Fireplace 都继承自该类。游戏中的瓷砖有自己的类(瓷砖),并在该瓷砖上有一个结构列表。我可以成功地在列表中包含的图块上构建结构。当我尝试从陷阱等类中访问函数时,问题就来了。它不起作用。我只能使用基类结构中的函数。

平铺列表:

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... 我想知道如何访问我不想使用的功能?

4

3 回答 3

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);
}
于 2013-01-31T09:01:25.087 回答
4

对电脑来说,s 只是一个Structure. 如果你想调用一个只有Fireplace类有但抽象类Structure没有的特定方法(例如,Fireplace类可能有一个BurnWood()对 a 没有意义的方法Structure),那么你想让计算机知道这Structure是实际上也是一个Fireplace(例如)。所以你可以通过铸造来做到这一点;例如:

((Fireplace)s).ColorBody(g, x - minx, y - miny); 

或者

(s as Fireplace).ColorBody(g, x - minx, y - miny); 

有关强制转换和使用运算符之间的区别,请参阅这篇文章as

于 2013-01-31T09:02:04.647 回答
1

正如我从您的问题中注意到的那样,您在两个类中有两个重载函数,即对于基类和派生类,您有不同的数字函数参数

在这种情况下,您必须支持编译类型多态性,如下所示

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

希望我在这里没有遗漏任何东西

于 2013-01-31T09:26:15.493 回答