我是初学者并且对此计划有疑问。我正在尝试从文本文件中读取表单属性。不幸的是,它只执行最后一行
这是我的文本文件
PDR
1 4 200 200 30 60 UserId
2 0 300 200 30 100 UserId
3 1 350 350 30 70 Log In
加载表单属性的构造函数
public Form()
{
{
string fn = Path.Combine(path, "Login.Production.txt");
string[] line;
if (File.Exists(fn))
{
try
{
line = File.ReadAllLines(fn);
string title = line[0];
if (title == "PDR")
{
for (int i = 1; i < line.Length; i++)
{
string[] pty = line[i].Split('\t');
Items = new List<IFormItem>();
Items.Add(new FormItem());
foreach (FormItem fi in Items)
{
fi.Type = (ItemTypes)Enum.Parse(typeof(ItemTypes), pty[1]);
fi.Id = Convert.ToInt32(pty[0]);
fi.X = int.Parse(pty[2]);
fi.Y = Convert.ToInt32(pty[3]);
fi.Height = Convert.ToInt32(pty[4]);
fi.Width = Convert.ToInt32(pty[5]);
fi.Text = pty[6].ToLower();
}
}
}
else
{
throw new Exception("The file is not cofigured.");
}
}
catch (Exception ex) { }
}
else
{
throw new FileNotFoundException("The file was not found.", fn);
}
}
}
答案 0 :(得分:2)
一个问题是,您为输入文件的每一行的新对象分配Items
;另一个是你为每一行输入迭代Items
的每个元素。这是修复它的一种方法:
if (title == "PDR")
{
Items = new List<IFormItem>();
for (int i = 1; i < line.Length; i++)
{
string[] pty = line[i].Split('\t');
FormItem fi = new FormItem();
Items.Add(fi);
fi.Type = (ItemTypes)Enum.Parse(typeof(ItemTypes), pty[1]);
fi.Id = Convert.ToInt32(pty[0]);
fi.X = int.Parse(pty[2]);
fi.Y = Convert.ToInt32(pty[3]);
fi.Height = Convert.ToInt32(pty[4]);
fi.Width = Convert.ToInt32(pty[5]);
fi.Text = pty[6].ToLower();
}
}
另一种方法是使用LINQ:
Items = (from l in line.Skip(1)
let pty = l.Split('\t')
select new FormItem
{
Type = (ItemTypes)Enum.Parse(typeof(ItemTypes), pty[1]),
Id = int.Parse(pty[0]),
X = int.Parse(pty[2]),
Y = int.Parse(pty[3]),
Height = int.Parse(pty[4]),
Width = int.Parse(pty[5]),
Text = pty[6].ToLower()
}).ToList<IFormItem>();