如何从文件动态创建对象?

时间:2021-10-03 02:47:42

I'm reading in files such as this with multiple lines like this.

我正在读这样的文件,有这样的多行。

"title,name,something,something,something"

How would I dynamically create new objects with those variables

如何使用这些变量动态创建新对象

I am splitting it already -

我已经拆分了 -

while (!reader.EndOfStream)
{
    lineFromFile = reader.ReadLine();

    split = lineFromFile.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);

}

My class is called Modules. Just don't know how to do it dynamically since I don't know how many modules will be in the file ETC.

我的班叫做模块。只是不知道如何动态地做它因为我不知道文件ETC中有多少个模块。

1 个解决方案

#1


2  

Create List<Module> and add all items read from your file there:

创建列表 并添加从您的文件中读取的所有项目:

List<Module> modules = new List<Module>();
while (!reader.EndOfStream)
{
    lineFromFile = reader.ReadLine();

    split = lineFromFile.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);

    var newModule = new Module();
    newModule.Property1 = split[0];
    newModule.Property2 = split[1];

    // (...) //

    modules.Add(newModule);

}

Or using LINQ:

或者使用LINQ:

var modules = (from line in File.ReadAllLines("fileName")
               let parts = line.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
               select new Module() {
                   Property1 = parts[0],
                   Property2 = parts[1],
                   Property3 = parts[2],
               }).ToList();

#1


2  

Create List<Module> and add all items read from your file there:

创建列表 并添加从您的文件中读取的所有项目:

List<Module> modules = new List<Module>();
while (!reader.EndOfStream)
{
    lineFromFile = reader.ReadLine();

    split = lineFromFile.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);

    var newModule = new Module();
    newModule.Property1 = split[0];
    newModule.Property2 = split[1];

    // (...) //

    modules.Add(newModule);

}

Or using LINQ:

或者使用LINQ:

var modules = (from line in File.ReadAllLines("fileName")
               let parts = line.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
               select new Module() {
                   Property1 = parts[0],
                   Property2 = parts[1],
                   Property3 = parts[2],
               }).ToList();