C# - 数组 - 异常错误 [英] C#- arrays - exception error
问题描述
这一行抛出IndexOutOfRangeException(索引超出了数组的边界),它在代码中的这一行指向:
This line throws IndexOutOfRangeException(index was outside the bounds of array) and it is pointed on this line in the code:
names[i] += txtName.Text + "\r\n";
只有当我停止输入名称时才会发生这种情况(比如说,在输入其中几个名字之后,点击显示名称按钮后,我会得到我输入的列表。但是当我再次继续输入名称时,我收到异常错误?
因此,如果我继续输入高达100的名字而不在中间点击节目名称,则没有错误。我应该能够在击中节目名称之后连续添加名称因为它不超过100个名字。
任何想法为什么?
This happens only if I stop entering names(lets say after entering few of them and after hitting show names button, I get the list that I entered. But when I continue entering name again, I get the exception error?
So if I continue entering names upto 100 without hitting show names in the middle, no error. I should be able to contunie add names after hitting the show names as long as it is not beyond 100 names.
Any ideas why?
<pre lang="C#">namespace Arrays
{
public partial class frmMain : Form
{
public frmMain()
{
InitializeComponent();
}
//initialize the Array
string[] names = new string[100];
int i = 0;
//Enter Names up to 100 and store them in array
private void btnEnterName_Click(object sender, EventArgs e)
{
names[i] += txtName.Text + "\r\n";
txtName.Clear();
}
//Display stored Names in Array using foreach loop in multiline textbox
private void btnShowNames_Click(object sender, EventArgs e)
{
foreach (var item in names)
{
txtNames.Text += names[i] + "\r\n";
i++;
}
}
}
}
我的尝试:
在指向错误的行之后尝试了i ++但没有成功。
What I have tried:
tried i++ after the line where error is pointed but no success.
推荐答案
你遇到变量i的问题:首先你要存储每个txtName .Text在同一个数组项(名称[0] - 这不是你想要的但它不是错误的来源)然后你增加i(在btnshowNames中)超出数组的大小(= 100)之前继续btnEntername,然后我太大(100)你得到错误。所以,不要一次使用一个变量用于多个目的。
让我们将我重命名为索引,你的代码应该是:
You're having problems with the variable i: first you're storing every txtName.Text in the same array-item (names[0] - that's not what you want but it's not the source of the error) and then you're increasing i (in btnshowNames) beyond the size of the array (= 100) before continuing with btnEntername where i is then too large (100) and you get the error. So, don't use a variable for more than one purpose at a time.
Let's rename i to index and your code should be:
private void btnEnterName_Click(object sender, EventArgs e)
{
if (index < names.Length)
{
names[index++] = txtName.Text;
txtName.Clear();
}
else
{
// array 'full'
}
}
private void btnShowNames_Click(object sender, EventArgs e)
{
txtName.Clear();
foreach (string item in names)
{
txtNames.AppendText(item + Environment.NewLine);
}
}
Peter
Peter
这篇关于C# - 数组 - 异常错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!