0

我正在制作一个用于学习的 2D 塔防游戏,我正在关注本教程:

http://xnatd.blogspot.com.br/2010/10/tutorial-9-multiple-waves.html

那里的代码使用波队列中的 Peek:

public Wave CurrentWave // Get the wave at the front of the queue

{
    get { return waves.Peek(); }
}

public List<Enemy> Enemies // Get a list of the current enemeies

{
    get { return CurrentWave.Enemies; }
}

public int Round // Returns the wave number

{
    get { return CurrentWave.RoundNumber + 1; }
}

但问题是,当队列中没有更多波时,它会崩溃:

“System.dll 中发生了‘System.InvalidOperationException’类型的未处理异常附加信息:空队列。”

它在代码的多个部分使用了这种方法。我试图在 GET 之前放置一个 IF,例如:

    public Wave CurrentWave // Get the wave at the front of the queue

    {
        if (waves.Count >= 1)
       {
        get { return waves.Peek(); }
       }
    }

但这似乎是不可能的。我不知道我该如何解决。

4

1 回答 1

1

只需将您的“if”放在方法主体中就可以了

该方法以“get {”开始,以“}”结束。那东西被称为属性获取器。

public Wave CurrentWave // Get the wave at the front of the queue
{    
    get 
    { 
       if (waves.Count >= 1)
       {
          return waves.Peek(); 
       }
       else
       {
          return null;
       }
    }
}

然后,修改另外两个 getter 以检查 CurrentWave 是否为 null,然后返回 null。

于 2015-01-20T18:27:25.100 回答