我取得了很大的进步,但现在我在加载文件时遇到了问题。下面是具有文件加载方法的类:
public class BunchOfDeliverables
{
private List<Person> myPersons;
private List<Deliverable> myDeliverables;
public BunchOfDeliverables()
{
this.myPersons = new List<Person>();
this.myDeliverables = new List<Deliverable>();
}
public List<Person> Persons { get { return this.myPersons; } }
public List<Deliverable> Deliverables { get { return this.myDeliverables; } }
public void LoadPersonsFromFile(String filename)
{
StreamReader sr = null;
try
{
sr = new StreamReader(new FileStream(filename, FileMode.Open, FileAccess.Read));
String name, street, housenr, postalcode, city;
name = sr.ReadLine();
while (name != null)
{
street = sr.ReadLine();
housenr = sr.ReadLine();
postalcode = sr.ReadLine();
city = sr.ReadLine();
this.myPersons.Add(new Person(name, street, Convert.ToInt32(housenr), postalcode, city));
name = sr.ReadLine();
name = sr.ReadLine(); //and again read a line, because of the delimiter (line with the stars)
}
}
catch (IOException) { }
finally
{
if (sr != null) sr.Close();
}
}
public void LoadDeliverablesFromFile(String filename)
{
StreamReader sr = null;
try
{
sr = new StreamReader(new FileStream(filename, FileMode.Open, FileAccess.Read));
String s;
s = sr.ReadLine();
while (s != null)
{
String[] items = s.Split();
this.myDeliverables.Add(new Deliverable(Convert.ToInt32(items[0]), Convert.ToInt32(items[1]), this.myPersons[Convert.ToInt32(items[2])]));
s = sr.ReadLine();
}
}
catch (IOException) { }
finally
{
if (sr != null) sr.Close();
}
}
public void AddPerson(Person p)
{
this.myPersons.Add(p);
}
public Deliverable FindDeliverable(int id)
{
foreach (Deliverable d in this.myDeliverables)
{
if (d.ID == id)
{
return d;
}
}
return null;
}
public void AddDeliverable(Deliverable d)
{
if (FindDeliverable(d.ID) == null)
{
myDeliverables.Add(d);
}
else
{
throw new Exception("Be aware: nothing is added!!!");
}
}
在这里 - 以我初始化它们的形式:
public partial class Form1 : Form
{
BunchOfDeliverables d;
public Form1()
{
InitializeComponent();
d = new BunchOfDeliverables();
d.LoadDeliverablesFromFile("../../data/deliverables.txt");
d.LoadPersonsFromFile("../../data/persons.txt");
}
private void button1_Click(object sender, EventArgs e)
{
listBox1.Items.Clear();
foreach (Person per in d.Persons)
{
listBox1.Items.Add(per);
}
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void ViewDeliv_Click(object sender, EventArgs e)
{
listBox1.Items.Clear();
foreach (Deliverable deliv in d.Deliverables)
{
listBox1.Items.Add(deliv);
}
}
现在对于 Persons 加载文件,它就像一个魅力,没有任何问题,但是一旦我尝试加载 Deliverables 文件,就会发生以下错误:
指数超出范围。必须是非负数且小于集合的大小。参数名称:索引”在这一行:
“this.myDeliverables.Add(new Deliverable(Convert.ToInt32(items[0]), Convert.ToInt32(items[1]), this.myPersons[Convert.ToInt32(items[2])]));”
下面是一个小例子(没有空行)的可交付成果文件的结构:
1 350 1
2 700 5
3 360 7
4 360 6
任何帮助,将不胜感激!