来自.bin文件的读取数据不正确

时间:2014-05-16 22:46:11

标签: c# serialization binaryfiles

我有两个课程:一个是学生考试,第二个是教师考试(教师创建一些测试变体并添加问题);教师程序通过测试创建.bin文件,然后学生打开并进行测试。数据结构(class Question)在两个程序中都类似; 老师的程序类代码:

[Serializable]
    public class Question
    {
        public Question(string q_text, Dictionary<string, bool> ans, Image img)
        {
            text = q_text;
            answers = ans;
            image = img;
            isAnswered = false;
        }
        public string text { get; set; }
        public Dictionary<string, bool> answers { get; set; }
        public Image image { get; set; }
        public bool isAnswered;

        public static void PersistObject(Dictionary<int, Question> q, Stream stream)
        {
            BinaryFormatter formatter = new BinaryFormatter();
            formatter.Serialize(stream, q);
            stream.Close();
        }

        public static Dictionary<int, Question> LoadObject(Stream stream)
        {
            try
            {
                BinaryFormatter formatter = new BinaryFormatter();

                Dictionary<int, Question> deserializedObject = (Dictionary<int, Question>)formatter.Deserialize(stream);
                stream.Close();
                return deserializedObject;
            }
            catch
            {
                return null;
            }
        }

    }
}

和学生的课程代码:

[Serializable]
    class Question
    {
        public Question(string text, Image img, Dictionary<string, bool> ans)
        {
            question_text = text;
            image = img;
            answers = ans;
            isAnswered = false;
        }
        public string question_text { get; set; }
        public Dictionary<string, bool> answers { get; set; }
        public Image image { get; set; }
        public bool isAnswered;

        public static Dictionary<int, Question> LoadObject(Stream stream)
        {
            try
            {
                BinaryFormatter formatter = new BinaryFormatter();

                Dictionary<int, Question> deserializedObject = (Dictionary<int, Question>)formatter.Deserialize(stream);
                stream.Close();
                return deserializedObject;
            }
            catch
            {
                return null;
            }
        }
    }

但是当我尝试在学生计划中阅读一些测试时:

string file =  path + test_number + ".bin";
Stream myStream = File.Open(file, FileMode.Open);
questions = Question.LoadObject(myStream);

它将questions设置为null。但是当我在教师程序中阅读这些文件时,它就可以了。(也许,它没关系,因为我也在教师模式下创建这些文件)。 questions的类型为Dictionary<int,Question>。问题是什么?

0 个答案:

没有答案
相关问题