我正在尝试将一个人的名字插入我的arraylist中的特定位置,我在运行时遇到错误:
public void InsertIntoArrayList(string actName, int posNum)
{
snip
}
用户可以在名称文本框中输入名称,然后输入插入字符串的位置(索引)。 有关更简单的编码方式的建议或我可以改变它的方式吗?
我得到的错误是 - the index is out of range
。我认为转换可能搞砸了?
答案 0 :(得分:2)
指数基于零。所以第一项是索引0,第十项是索引9. ArrayList.Insert
:
int posNum;
if(!int.TryParse(txtPosition.Text, out posNum))
{
// show message
return;
}
else if(posNum < 0 || posNum > ActorArrayList.Count)
{
// show message
return;
}
ActorArrayList.Insert(posNum, actName);
如果你想在最后添加对象,你只需要使用Add
:
ActorArrayList.Add(actName);
注意:您应该使用强类型List<T>
而不是ArrayList
,同时它们是多余的。 c# When should I use List and when should I use arraylist?
答案 1 :(得分:0)
您总是可以在数组上使用.ToList,然后使用List插入函数。