Random r = new Random();
int InvadorNumberA=r.Next(0,5);
int randomShot = r.Next(5);
List<Invaders> invadersShooting = new List<Invaders>();
Invaders invaderA=new Invaders();
var invaderByLocationX = from invadersSortByLocation in invaders
group invadersSortByLocation by invadersSortByLocation.Location.Y
into invaderGroup
orderby invaderGroup.Key
select invaderGroup;
invadersShooting = invaderByLocationX.Last().ToList();
try
{
invaderA = invadersShooting[InvadorNumberA];// constantly being thrown there. i cant catch the exception.. so i guess it is being thrown somewhere else. any idea on how i stop it from being thrown?
}
catch(ArgumentOutOfRangeException dd)
{
invaderA = invadersShooting[0];
}
堆栈跟踪
" 在 System.ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument argument, ExceptionResource resource) 处引发异常\r\n 在 System.ThrowHelper.ThrowArgumentOutOfRangeException() 处引发异常\r\n 在 System.Collections.Generic.List`1.get_Item(Int32 index) 处引发异常\r\n 在 WindowsFormsApplication1.Game.ReturnFire() 位置 D:\Documents and Settings\Dima\My Documents\Visual Studio 2008\Projects\SpaceInvaders\SpaceInvaders\SpaceInvadorGame\Game.cs:line 444"
目标站点
{Void ThrowArgumentOutOfRangeException(System.ExceptionArgument, System.ExceptionResource)}
更多信息:
{"Index was out of range. Must be non-negative and less than the size of the collection.\r\nParameter name: index"}
{"索引超出范围。必须是非负数且小于集合大小。\r\n参数名: index"}
我通过简单地执行以下操作来解决异常
invadersShooting = invaderByLocationX.Last().ToList();
invaderA = invadersShooting[r.Next(0,invadersShooting.Count)];
但我仍然很好奇,异常是在哪里抛出的...嗯
random.Next(0, 0)
将返回0(我几乎期望它会失败)。在空列表中,将没有索引为0的元素。请验证! - Anthony Pegram