ArgumentOutofRangeException

Dmi*_*iyd 4 c# arguments exception-handling

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];
       }
Run Code Online (Sandbox Code Playgroud)

堆栈跟踪

"在System.ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument参数,ExceptionResource资源)\ r \n在System.ChrowHelper.ThrowArgumentOutOfRangeException()\ r \n在System.Collections.Generic.List`1.get_Item(Int32 index)\ r \n在D:\ Documents and Settings\Dima\My Documents\Visual Studio 2008\Projects\SpaceInvaders\SpaceInvaders\SpaceInvadorGame\Game.cs中的WindowsFormsApplication1.Game.ReturnFire():第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"}
Run Code Online (Sandbox Code Playgroud)

{"索引超出范围.必须是非负数且小于集合的大小.\ r \nParameter name:index"}

我只是通过这样做摆脱了异常

 invadersShooting = invaderByLocationX.Last().ToList();

           invaderA = invadersShooting[r.Next(0,invadersShooting.Count)];
Run Code Online (Sandbox Code Playgroud)

但我仍然好奇,抛出异常的地方......嗯

Ant*_*ram 8

不要这样做.

例外应该是例外.你有办法防止这种特殊情况,你绝对应该这样做.

invaderA = invadersShooting[InvadorNumberA];
invaderA = invadersShooting[0]; 
Run Code Online (Sandbox Code Playgroud)

在第一种情况下,InvadorNumberA可以是0到4之间的任何InvadorNumberA + 1内容.在尝试从中获取元素之前,检查并查看列表中是否至少包含元素.不要依赖例外来纠正你的课程.不仅如此,也许InvadorNumberA应该实际上受到限制random.Next(0, list.Count).为什么在列表中只有1个或2个元素时创建一个从0到4的数字?