使用方法RemoveRange时List中的ArgumentOutOfRange

所以我有一个包含379个元素的列表,我想删除其中的最后8个元素

我正在使用

List<Point> points= new List<Point>();
...
points.RemoveRange(points.Count-8,8);

但它抛出ArgumentOutOfRangeException

需要非负数。参数名称:索引

所以我有清单的课看起来像这样

上课要点:


namespace XanMan.NET

{

    class Point

    {

        protected Texture texture;

        protected RectangleShape body;

        protected Vector2f position;

        public const uint point = 10;


        public Point(Vector2f position)

        {

            texture = new Texture("point.png");

            body = new RectangleShape(new Vector2f(10, 10))

            {

                Texture = texture,

                Position = position

        };


        }

        protected Point()

        {

        }


        public void Draw(RenderWindow window)

        {

            window.Draw(body);

        }

    }

}

和program.cs与主要


class Program

{

    static RenderWindow window;

    static GAMESTATE gamestate;

    static Map map;

    static Menu menu;


    static void Main(string[] args)

    {

        window = new RenderWindow(new VideoMode(1280, 780), "XanMan.NET");

        gamestate = GAMESTATE.mainmenu;

         menu = new Menu(gamestate);

        map = new Map();

        PointsMap mapOfPoints = new PointsMap();

        window.Closed += Window_Closed;

        window.KeyReleased += menu.Update;



        while (window.IsOpen)

        {

            window.DispatchEvents();

            window.Clear();

            map.Draw(window);

            mapOfPoints.Draw(window);

            window.Display();

        }

    }


    private static void Window_Closed(object sender, EventArgs e) => window.Close();

}

我已经删除了PointsMap中的一些循环,但是您已经知道发生了什么。


料青山看我应如是
浏览 172回答 1
1回答

凤凰求蛊

您的绘制函数假设removerange索引和offset是8的倍数。情况似乎并非如此:points.Count%8!=0。您可以使用下面的代码来处理其余的代码。&nbsp; &nbsp; public void Draw(RenderWindow window)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; var n = 8;&nbsp; &nbsp; &nbsp; &nbsp; var index = Math.Max(0, points.Count - n);&nbsp; &nbsp; &nbsp; &nbsp; var offset = Math.Min(points.Count, n);&nbsp; &nbsp; &nbsp; &nbsp; points.RemoveRange(index, offset);&nbsp; &nbsp; &nbsp; &nbsp; foreach (Point point in points)&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;point.Draw(window);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp;}
打开App,查看更多内容
随时随地看视频慕课网APP