如何将类列表保存在文件中?我可以通过控制台显示列表的某些类别吗?

时间:2019-04-10 18:37:49

标签: c# .net

假设有一个“雇员”类。它具有名称(字符串)和描述(字符串)。

我列出了一个名为“ Employees”的列表,该列表应该包含具有不同参数的不同“ Employee”类。

我尝试用foreach运算符显示它,但是,它仅返回“ .Employee”字符串。

using System;
using System.Collections.Generic;

namespace Work
{
    // Employee class
    public class Employee
    {
        public int ID;
        public string Name;
        public string Description;
    }

    class Program
    {

        // Create a list
        List<Employee> employees = new List<Employee>();

        // Add new employye method
        private void CreateEmployee(int id, string name, string description)
        {
            Employee employee = new Employee();
            employee.ID = id;
            employee.Name = name;
            employee.Description = description;

            employees.Add(employee);
        }

        static void Main(string[] args)
        {
            // Neccessary because void Main() is static field
            Program P = new Program();
            // Calling method and adding new employee with new parameters to the list
            P.CreateEmployee(1, "James", "Funny");

            // Now's the question:
            // How to access this data?
            // I would like to make a file which would contain all information in the list, which I can read and load in a list again
            // Or just at least display it to the console
        }
    }
}

基本上,我想要一个像这样的文件:

1,"James","Funny";
2,"John","Just John";

不过,我不确定“” 对于保存字符串是否必要。

1 个答案:

答案 0 :(得分:1)

正确地讲,为什么要创建Program类的实例,只需制作方法以及列表static并直接在Main方法中使用它们。

第二,为什么创建方法CreateEmployee?只需为您的Employee类定义构造函数,即可完成为字段分配值的工作。

最后,您要寻找的是Employee类型的对象的字符串表示形式。覆盖ToString方法是这里的关键。

所以您的班级应该像这样:

public class Employee
{
    public int ID;
    public string Name;
    public string Description;

    public Employee(int ID, string Name, string Description)
    {
        this.ID = ID;
        this.Name = Name;
        this.Description = Description;
    }

    public override string ToString()
    {
        return $"{ID}, {Name}, {Description}";
    }
}

有了这个,您可以这样编写Main方法:

List<Employee> employees = new List<Employee>();
employees.Add(new Employee(1, "James", "Funny"));
File.WriteAllLines("file path", employees.Select(e => e.ToString()).ToArray();