代码之家  ›  专栏  ›  技术社区  ›  blazing

如何将Student对象写入C中的文件#

c#
  •  -2
  • blazing  · 技术社区  · 8 年前
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.IO;
    
    namespace WriteStudents
    {
        class Student
        {
            public String name;
            public int mark;
    
            public Student(String n, int m)
            {
                name = n;
                mark = m;
            }
            public override string ToString()
            {
                return name + " " + mark;
            }
            void print(Student[] group)
            {
                for (int i = 0; i < group.Length; i++)
                    Console.WriteLine(group[i]);
            }
        }
    
        class Program
        {
            static void Main(string[] args)
            {
                String filePath = @"C:\Users\Path\students.txt";
                String[] lines = File.ReadAllLines(filePath);
    
                Student[] group = new Student[lines.Length];
    
                for (int i = 0; i < lines.Length; i++)
                {
                    String[] tokens = lines[i].Split(); //split the names from the marks;
                    group[i] = new Student(tokens[0], int.Parse(tokens[1]));
                }
    
                File.WriteAllLines(filePath, group); //error is here
    
            }
        }
    }
    

    在本练习中,您将从文件中读入一组学生。然后将每个学生的分数增加1,并将结果写入另一个文件。文件的格式将与上一练习中的格式相同。输入文件的名称将是第一个参数,输出文件的名称将是第二个参数。

    例如,如果输入文件为:

    John 50
    Abby 40
    

    您的程序将创建以下文件:

    John 51
    Abby 41
    

    伙计们,我怎样才能将我的学生对象写入文件?它不允许我将学生对象转换为字符串对象。有什么想法吗?

    1 回复  |  直到 8 年前
        1
  •  1
  •   Black Frog    8 年前

    方法 File.WriteAllLines 仅将字符串[]作为要输出的数据。您正在传递 Student 对象

    您需要获取对象的字符串表示形式,并将其传递给write函数。

    这只是众多方法之一:

    static void SaveAllStudentsToFile(string fileName, Student[] group)
    {
        // create a place to hold data
        string[] data = new string[group.Length];
    
        int counter = 0;
        for (int i = 0; i < group.Length; i++)
        {
            data[i] = group[i].ToString();
        }
    
        // now write the data to a file
        File.WriteAllLines(fileName, data);
    }