无法将对象强制转换为列表

本文关键字:转换 列表 对象 | 更新日期: 2023-09-27 18:26:28

我有一段代码,试图将我创建的对象强制转换为列表,但它不会将对象强制转换到列表。我不知道为什么会发生这种事。

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;
    }
}

我只是想弄清楚为什么它在过去这样做的时候不会把对象投射到列表中。如能在这件事上提供任何帮助,我们将不胜感激。

无法将对象强制转换为列表

错误似乎表明您序列化了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;
相关文章: