[英]C# Array Index Error
我要添加的简单数组,但是不断出现“索引越界”错误。 环顾四周,无法完全弄清楚我要去哪里,我认为这与我使用pos变量的地方有关。 发表任何我认为可能相关的内容。 提前致谢。
const int MAX = 5;
Account[] db = new Account[MAX];
// global variable for position in array
int pos;
private void Form1_Load(object sender, EventArgs e)
{
// initialise the array with instantiated objects
for (int i = 0; i < MAX; i++)
db[i] = new Account();
}
private void OpenAcc_Click(object sender, EventArgs e)
{
//hide menu
hide_menu();
//make new form elements visible
tbNameEnt.Visible = true;
tbBalaEnt.Visible = true;
SubDet.Visible = true;
//set pos to the first empty element of array
pos = Array.FindIndex(db, i => i == null);
}
private void SubDet_Click(object sender, EventArgs e)
{
string textBox1;
double textBox2;
int a = 0011228;
int b = pos + 1;
int accNo;
//get and parse input details
textBox1 = tbNameEnt.Text;
textBox2 = double.Parse(tbBalaEnt.Text);
//allocate account number
accNo = int.Parse(a.ToString() + b.ToString());
//set details for new object in array
db[pos].SetAccount(textBox1, accNo, textBox2); //ERROR HERE
//print account created confirmation message
ConfMess();
//OK button then takes us back to menu
}
Array.FindIndex
将根据谓词返回位置,如果匹配的项均不返回-1
,对于您的情况,您将在数组中分配数组的每个元素
for (int i = 0; i < MAX; i++)
db[i] = new Account();
这将确保没有任何项目为null,因此从Array.FindIndex返回-1
,随后在您使用该位置pos
访问数组元素时,您将获得异常。
这行:
pos = Array.FindIndex(db, i => i == null);
在执行以下操作时, pos
设置为-1
:
db[pos].SetAccount(textBox1, accNo, textBox2);
您将获得例外。
您可以使用实例化的Account对象初始化数组。
不能保证FindIndex()调用将返回有效位置(即pos将被分配为-1)
之后,您可以参考db [-1],这将引发异常。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.