-1

我有以下代码。在其中我将某些内容保存到列表中,并且我希望将这两个列表保存在 XML 文件中,但是程序在尝试调试时中断了“51”行。

接下来的事情:

XmlSerializer xs = new XmlSerializer(typeof(T));

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using System.IO;
using System.Xml.Serialization;

namespace Maman15cs
{

    public class XSerial
    {
        /// <summary>
        /// Save an instance of a class to an XML file
        /// </summary>
        /// <param name="filename">Full or relative path to the file</param>
        /// <param name="cls">Class to serialize and save.</param>
        /// <param name="t">Type of the class (use: typeof(ClassName)</param>
        /// <returns>True on success, False on failure</returns>
        public static void Save<T>(string filename, T cls)
        {
            using (Stream s = File.Open(filename, FileMode.Create))
            {
                using (StreamWriter sw = new StreamWriter(s))
                {
                    sw.Write( SerializeObject<T>(cls) );
                    sw.Close();
                    s.Close();
                    return;
                }
            }
        }


        /// <summary>
        /// Serialize the object into an XML format
        /// </summary>
        /// <typeparam name="T">Type of object to serialize</typeparam>
        /// <param name="pObject">the object to serialize</param>
        /// <returns>a string representing the XML version of the object</returns>
        public static String SerializeObject<T>(T pObject)
        {
            MemoryStream memoryStream = new MemoryStream();
            UTF8Encoding encoding = new UTF8Encoding();

            XmlSerializer xs = new XmlSerializer(typeof(T));
            System.Xml.XmlTextWriter xmlTextWriter = new System.Xml.XmlTextWriter(memoryStream, Encoding.UTF8);
            xs.Serialize(xmlTextWriter, (object) pObject);
            memoryStream = (MemoryStream)xmlTextWriter.BaseStream;
            return encoding.GetString(memoryStream.ToArray());
        }

        /// <summary>
        /// Deserialize the object back into the object from an XML string
        /// </summary>
        /// <typeparam name="T">Type of the object to restore</typeparam>
        /// <param name="pXmlizedString">The string that represents the object in XML</param>
        /// <returns>A new instance of the restored object</returns>
        public static T DeserializeObject<T>(String pXmlizedString)
        {
            UTF8Encoding encoding = new UTF8Encoding();
            XmlSerializer xs = new XmlSerializer(typeof(T));
            MemoryStream memoryStream = new MemoryStream(encoding.GetBytes(pXmlizedString));
            System.Xml.XmlTextWriter xmlTextWriter = new System.Xml.XmlTextWriter(memoryStream, Encoding.UTF8);
            return (T)xs.Deserialize(memoryStream);
        }
    }

    public class ClassRoom
    {
        public string ClassNumber{ get; set; }
        public int NumberofPlaces { get; set; }
        public string[,] DayandHour = new string[6, 8];

        public static ClassRoom AddClassRoom()
        {
            var classRoom = new ClassRoom();
            Console.WriteLine("Enter the Class number, the Number of places\n");
            classRoom.ClassNumber = Console.ReadLine();
            classRoom.NumberofPlaces = int.Parse(Console.ReadLine());

            return classRoom;
        }

        public ClassRoom AddCourseInClassroom(ClassRoom classroom, string courseNum)
        {
            for (int i = 0; i < 6; i++)
            {
                for (int j = 0; j < 8; j++)
                {
                    if (String.IsNullOrEmpty(classroom.DayandHour[i, j]))
                    {
                        classroom.DayandHour[i, j] = courseNum;
                        return classroom;
                    }
                }
            }
            return null;
        }

        public void PrintClassRoom(ClassRoom classroom)
        {
            for (int i = 0; i < 6; i++)
            {
                for (int j = 0; j < 8; j++)
                {
                    if (!(String.IsNullOrEmpty(classroom.DayandHour[i, j])))
                    {
                        Console.WriteLine(" {0}", classroom.DayandHour[i, j]);

                    }
                }
                Console.WriteLine("\n");
            }
        }

        public void PrintList<T>(IEnumerable<T> col)
        {
            foreach (var item in col)
                Console.WriteLine(item);
        }

        public void DeleteCourse(string coursenum, ClassRoom classroom)
        {
            for (int i = 0; i < 6; i++)
            {
                for (int j = 0; j < 8; j++)
                {
                    if (classroom.DayandHour[i, j] == coursenum)
                    {

                        classroom.DayandHour[i, j] = null;
                    }
                }
            }
        }
    }


    public class Course
    {
        public string CourseName;
        public string CourseNumber;
        public int StudentsNumber;
        public string TeacherName;
        public string ClassNumber;

        public static Course AddCourse()
        {
            Course newCourse = new Course();
            Console.WriteLine("Enter the Course's name, course's number, students number, teacher's name, and class' number\n");
            newCourse.CourseName = Console.ReadLine().ToString();
            newCourse.CourseNumber = Console.ReadLine();
            newCourse.StudentsNumber = int.Parse(Console.ReadLine());
            newCourse.TeacherName = Console.ReadLine().ToString();
            newCourse.ClassNumber = Console.ReadLine().ToString();
            return newCourse;
        }

        public void PrintCourse(Course course)
        {
            Console.WriteLine("The course name is " + course.CourseName);
            Console.WriteLine("\nThe course number is " + course.CourseNumber);
            Console.WriteLine("\nThe class number is " + course.ClassNumber);
            Console.WriteLine("\nThe students number is " + course.StudentsNumber);
            Console.WriteLine("\nTeacher's name is " + course.TeacherName + "\n");
        }
    }

    public class Program
    {
        static void Main(string[] args)
        {
            var course = new List<Course>();
            var classroom = new List<ClassRoom>();

            bool loop = true;

            int actionChoice;

            while (loop == true) {
                Console.WriteLine("What do you want to do? (Enter number): \n 1)Add a new Course \n 2)Add a new class room \n 3)Add an existing course to an existing classroom \n 4)Read the information of a specific classroom \n 5)Read the information of all the classrooms \n 6)Read the information of a specific course \n 7)Delete a specific course in a specific classrom \n 8)Exit the program  \n");
                actionChoice = int.Parse(Console.ReadLine());

                switch (actionChoice)
                {
                    case 1: //Add a new Course

                        var new_course =  Course.AddCourse();
                        course.Add(new_course);
                        break;

                    case 2:

                       var new_classRoom = ClassRoom.AddClassRoom();
                       classroom.Add(new_classRoom);
                       break;

                    case 3:
                        Console.WriteLine("Enter the course's number and the classroom's number");
                        var courseNumber = Console.ReadLine();
                        var classroomNumber = Console.ReadLine();

                        foreach (ClassRoom room in classroom)
                        {
                            if (room.ClassNumber == classroomNumber)

                                room.AddCourseInClassroom(room, courseNumber);
                        }

                        foreach(Course _course in course)
                        {
                            if(_course.CourseNumber == courseNumber)
                                _course.ClassNumber = classroomNumber;
                        }
                        break;

                    case 4:
                        Console.WriteLine("Enter the classroom number");
                        classroomNumber = Console.ReadLine();

                        foreach (ClassRoom room in classroom)
                        {
                            if (room.ClassNumber == classroomNumber)
                            {
                                room.PrintClassRoom(room);
                            }
                        }
                        break;

                    case 5:
                        foreach (ClassRoom room in classroom)
                        {
                            room.PrintClassRoom(room);
                        }
                        break;

                    case 6:
                        Console.WriteLine("Enter the course number");
                        courseNumber = Console.ReadLine();

                        foreach (Course ccourse in course)
                        {
                            if (ccourse.CourseName == courseNumber)
                                ccourse.PrintCourse(ccourse);
                        }
                        break;

                    case 7:
                        Console.WriteLine("Enter the course's number and the classroom's num");
                        courseNumber = Console.ReadLine();
                        classroomNumber = Console.ReadLine();

                        foreach (ClassRoom classRoom in classroom)
                        {
                            if (classRoom.ClassNumber == classroomNumber)
                                classRoom.DeleteCourse(courseNumber, classRoom);
                        }
                        break;

                    case 8:
                        loop = false;
                        break;
                }
            }

            XSerial.Save("Course.xml", course);
            XSerial.Save("Classroom.xml", classroom);
        }
    }
}

如果有人能帮我完成这个,并纠正部分(我怀疑问题来自方法 SerializeObject)。

4

2 回答 2

1

你应该改变这一行

public string[,] DayandHour = new string[6, 8];

类,因为Xml 序列化不支持ClassRoom多维数组。

于 2013-09-27T16:32:01.723 回答
-1

Take a look at the Reflection API which is used to determine types dynamically at runtime.

typeof vs GetType() : Type Checking: typeof, GetType, or is?

Reflection API: http://msdn.microsoft.com/en-us/library/ms173183%28v=vs.90%29.aspx

于 2013-09-27T16:21:05.923 回答