【发布时间】:2011-12-03 01:10:05
【问题描述】:
我有这部分代码,它获取一个文件并将其放入ArrayList。将输入的文件将是CSV(我使用的当前CSV 在第一行有标题,所以我不需要那行),第二行必须放在ArrayList .
我使用ArrayList,因为文件可以是动态的,所以我不确定第二行的长度是多少。我测试了(在第二行使用一个包含 7 个逗号分隔值的文件)这段代码,它打印出 ArrayList 的长度为 (fileList.Count) = 1。
怎么了?
ArrayList fileList2 = new ArrayList();
private void button3_Click(object sender, EventArgs e)
{
string filename = "";
DialogResult result = openFileDialog2.ShowDialog();
if (result == DialogResult.OK)
{
filename = openFileDialog2.FileName;
textBox3.Text = filename;
string line2;
System.IO.StreamReader file2 = new System.IO.StreamReader(textBox3.Text); //reads file from textbox
stringforData = file2.ReadLine(); // this reads the first line that I dont need
while ((line2 = file2.ReadLine()) != null) //read the lines
{
// puts elements into array
fileList2.Add(line2.Split(';'));//split the line and put it in the arraylist
}
file2.Close();
if (true) // this is for testind what is happening
{
this.textBox2.Clear();
textBox3.Text = Convert.ToString(fileList2.Count);
}
}
}
【问题讨论】:
-
你到底为什么在 2011 年使用 arraylist?它已被弃用多年,如果 Baszz 是正确的,您的示例就说明了原因
-
要补充 Dyppl 所说的内容,请参阅 this question。
-
@Dyppl 我应该使用什么以及如何使用?
-
@georgemano:你应该使用generis
List<T>:msdn.microsoft.com/en-us/library/6sh2ey19.aspx,我想在你的情况下它将是List<string>。ArrayList在泛型之前就有了,现在没有必要在新代码中使用它了。