首页 > 解决方案 > C# 中的“超出数组范围”错误

问题描述

这里是初学者的问题。我正在尝试运行此代码。我有点想将另一个数组的顺序更改为这个新数组。但是,我收到错误 System.IndexOutOfRangeException: 'Index out of bound from array'

我真的不知道该做什么或我做错了什么。

 public partial class Form3 : Form
    {
        public string[] arrayJugadores = new string[3];
        Form2 FormRegistro = new Form2();
        public Form3()
        {
            InitializeComponent();

            Random randomizador = new Random();
            int valor = randomizador.Next(1, 15);

            if (valor == 1)
            {
                arrayJugadores[0] = FormRegistro.listaJugadores[0];
                arrayJugadores[1] = FormRegistro.listaJugadores[1];
                arrayJugadores[2] = FormRegistro.listaJugadores[2];
                arrayJugadores[3] = FormRegistro.listaJugadores[3];
            }
            else if (valor == 2)
            {
                arrayJugadores[0] = FormRegistro.listaJugadores[3];
                arrayJugadores[1] = FormRegistro.listaJugadores[0];
                arrayJugadores[2] = FormRegistro.listaJugadores[1];
                arrayJugadores[3] = FormRegistro.listaJugadores[2];
            }

标签: c#windowsforms

解决方案


使您的数组更大,它目前只能容纳 3 个元素:

public string[] arrayJugadores = new string[4];

另外,检查错误消息及其出现在哪一行,然后您应该能够弄清楚。


推荐阅读