【发布时间】:2019-04-30 01:59:25
【问题描述】:
我创建了一个非常简单的类,我正在尝试使用 List 类从文本文件读取到列表中。
我使用 StreamReader inputFile 打开文件,但是当我尝试使用 ReadLine 时出现错误,我无法将字符串转换为...。Bowler(这是我列表中的名称。
我创建了这个类,以便我可以从多个表单访问列表。 我显然是 C# 的新手,并且是一般的编程新手。
//the ReadBowlers method reads the names of bowlers
//into the listBowlers.
private void ReadBowlers(List<Bowler> listBowlers)
{
try
{
//Open the Bowlers.txt file.
StreamReader inputFile = File.OpenText("Bowlers.txt");
//read the names into the list
while (!inputFile.EndOfStream)
{
listBowlers.Add(inputFile.ReadLine());
}
//close the file.
inputFile.Close();
}
catch (Exception ex)
{
//display error message
MessageBox.Show(ex.Message);
}
给我错误的行是: listBowlers.Add(inputFile.ReadLine());
【问题讨论】:
-
程序不知道如何将字符串转换为您的类。您需要告诉它如何手动执行此操作。您可以发布您的
Bowler课程吗? -
您试图以错误的方式使用文件流。建议阅读
https://docs.microsoft.com/en-us/dotnet/api/system.io.filestream?view=netframework-4.7.2 -
@Loocid My Bowler Class
codeclass Bowler { //fields private string _name; //构造函数 public Bowler() { _name = Name; } //名称属性 public string Name { get;放; }code -
我显然不太擅长这个,55岁开始学习
-
如果您尝试将对象(Bowler)数据存储到磁盘并读回 - 研究序列化。在 4 或 5 行代码中保存或加载数据。
标签: c#