无法将对象转换为列表

时间:2014-10-15 00:37:53

标签: c# list

我有一段代码,我正在尝试将一个对象转换为列表,并且不会将对象强制转换为列表。我不知道为什么会这样。

FileStream fs = new FileStream("students.dat", FileMode.Open);
BinaryFormatter bf = new BinaryFormatter();
List<Student> studentList = (List<Student>)bf.Deserialize(fs);

最后一行的代码错误说:

Unable to cast object of type 'Project.Student' to type 'System.Collections.Generic.List`1[Project.Student]'.

对象创建如下所示:

[Serializable]
class Student
{
    private String name;
    private String surname;
    private String id;
    private int lab;
    private int assign1;
    private int assign2;
    private int exam;

    public Student(String name, String surname, String id)
    {
        this.name = name;
        this.surname = surname;
        this.id = id;
        this.lab = 0;
        this.assign1 = 0;
        this.assign2 = 0;
        this.exam = 0;
    }
    public Student(String name, String surname, String id, int lab, int assign1, int assign2, int exam)
    {
        this.name = name;
        this.surname = surname;
        this.id = id;
        this.lab = lab;
        this.assign1 = assign1;
        this.assign2 = assign2;
        this.exam = exam;
    }
}

我只想弄清楚为什么在过去这样做时它不会将对象强制转换为列表。任何有关此事的帮助将不胜感激。

1 个答案:

答案 0 :(得分:1)

该错误似乎表示您序列化了Student而不是List<Student>

如果有可能被序列化,那么只需检查演员并为Student案例制作一个新列表:

object readObject = bf.Deserialize(fs);
if (readObject is List<Student>)
   return (List<Student>)readObject
else if (readObject is Student)
   return new List<Student>() { (Student)readObject };
else
   return null;
相关问题