【发布时间】:2021-11-22 13:38:18
【问题描述】:
我的代码有 4 个类(id、books、teachers、courses) 我的代码的目的很简单我向用户询问文本文件的路径,然后从文本文件中读取每一行,但我必须使用类,每个类我都为文本文件的路径和一个 try, catch 函数放置了一个代码来读取它,我的问题是我应该如何或应该使用什么函数来读取我 (Program.cs) 中的类中的行) 例如,这是我的一门课程中的代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace ConsoleApplication4
{
class books
{
static void Main(string[] args)
{
String line;
try
{
//Pass the file path and file name to the StreamReader constructor
StreamReader books = new StreamReader(@"C:\Users\R\Desktop\svu\programming_2\s21\books.txt");
//Read the first line of text
line = books.ReadLine();
//Continue to read until you reach end of file
while (line != null)
{
//write the line to console window
Console.WriteLine(line);
//Read the next line
line = books.ReadLine();
}
//close the file
books.Close();
Console.ReadLine();
}
catch (Exception e)
{
Console.WriteLine("Exception: " + e.Message);
}
finally
{
Console.WriteLine("Executing finally block.");
}
}
}
}
【问题讨论】:
-
你的意思是这样的:DotNetFiddle:ClassFromLines
-
从您的问题中不清楚您到底要做什么以及您的问题到底是什么。您的示例代码没有显示任何类,并且很难知道您要做什么。
-
答案的一半在于问题本身。您确定 “id, books,teachers, courses” 与 ONE 课程的
classes不同,而不是properties或fields?你在“但我必须使用类”下是什么意思?使用类存储从文件中读取的数据?还是使用类从文件中读取数据? -
@PaulF 我的问题是我在我的程序中添加了多个类。每个类看起来都像代码在我的问题中,我如何在原始程序中使用例如 streamReader 函数,我的书籍类。 cs
-
@Auditive 例如,我的书籍类中有一个流阅读器功能,我如何在我的 program.cs 中使用它
标签: c# visual-studio class