1
            List<Invaders> invadersShooting = new List<Invaders>();
        Invaders invaderA=new Invaders();
    try
            {
        var invaderByLocationX = from invadersSortByLocation in invaders
                                 group invadersSortByLocation by invadersSortByLocation.Location.Y
                                 into invaderGroup
                                 orderby invaderGroup.Key
                                 select invaderGroup;

        if (invaderByLocationX != null)
        {

                invadersShooting = invaderByLocationX.Last().ToList();// it is being throwing constantly here.. How can i prevent it from being thrown

                invaderA = invadersShooting[r.Next(0, invadersShooting.Count)];




                if (r.Next(5) < 4 - randomShot)
                {
                    Invadershots.Add(new Shot(invaderA.Location, Direction.DOWN, gameBoundaries, WEAPON.DEFAULT, isWeapon));
                }
        }
            }
    catch (Exception e)
    { }
    }

我怎样才能防止错误发生?如何让程序检查invaderByLocationX 是否为空?因为它是空的,因此抛出异常:(

4

1 回答 1

2

LastOrDefault如果序列为空,您可以使用which 将返回 null 。然后,您将要检查 null。

var invader = invaderByLocationX.LastOrDefault();
if(invader == null)
{
    // do something
}
else
{
    invaderA = invadersShooting[r.Next(0, invadersShooting.Count)];
    // etc
}

另请注意,invaderByLocationX 永远不能为空,因此不需要检查空值。

于 2011-04-17T10:01:24.627 回答