从IList <t>加载并保存到文本

时间:2015-06-04 12:04:12

标签: c#

这是我的代码 -

class Appointments:IAppointments
{
    private readonly IList<IAppointment> _list = new List<IAppointment>(); 

    public Appointments()
    {

    }

    public bool Load()
    {
        throw new NotImplementedException();
    }

    public bool Save()
    {
        throw new NotImplementedException();
    }

    public IEnumerable<IAppointment> GetAppointmentsOnDate(DateTime date)
    {
        throw new NotImplementedException();
    }

    public int IndexOf(IAppointment item)
    {
        return _list.IndexOf(item);
    }

    public void Insert(int index, IAppointment item)
    {
        _list.Insert(index, item);
    }

    public void RemoveAt(int index)
    {
        _list.RemoveAt(index);
    }

    public IAppointment this[int index]
    {
        get
        {
            return _list[index];
        }
        set
        {
            _list[index] = value;
        }
    }

    public void Add(IAppointment item)
    {
        _list.Add(item);
    }

    public void Clear()
    {
        _list.Clear();
    }

    public bool Contains(IAppointment item)
    {
        return _list.Contains(item);
    }

    public void CopyTo(IAppointment[] array, int arrayIndex)
    {
        _list.CopyTo(array, arrayIndex);
    }

    public int Count
    {
        get { return _list.Count; }
    }

    public bool IsReadOnly
    {
        get { return _list.IsReadOnly; }
    }

    public bool Remove(IAppointment item)
    {
        return _list.Remove(item);
    }

    public IEnumerator<IAppointment> GetEnumerator()
    {
        return _list.GetEnumerator();
    }

    System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
    {
        foreach (IAppointment item in _list)
        {
            if (item == null)
            {
                break;
            }

            yield return item;
        }

我想知道如何进行加载和保存方法。 save方法需要保存到文本文件。 load方法需要从txt文件加载。

IAppointment interface -

 namespace Calendar
    {
        public interface IAppointment
        {
            DateTime Start { get; }
            int Length { get; }
            string DisplayableDescription { get; }
            bool OccursOnDate(DateTime date);
        }
    }

该网站抱怨说这主要是代码,所以我要写这个毫无意义的句子,直到它有希望消失。感谢您的耐心等待。

3 个答案:

答案 0 :(得分:0)

这是序列化代码

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

namespace Calendar
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        static void Main(string[] args)
        {
            //add to appointments to object below
            Appointments appointments = new Appointments()
            {
                appointments = new List<Appointment>() {
                    new Appointment(){ start = DateTime.Today, length = 2, displayableDescription = "Meeting wiith Joe", occursOnDate = true},
                    new Appointment(){ start = DateTime.Today.AddDays(2), length = 3, displayableDescription = "Meeting wiith Jane", occursOnDate = false}
                }
            };


            //use this code for writing
            XmlSerializer serializer = new XmlSerializer(typeof(Appointments));

            StreamWriter writer = new StreamWriter(FILENAME);
            serializer.Serialize(writer, appointments);
            writer.Flush();
            writer.Close();
            writer.Dispose();

            //use this code for reading
            XmlSerializer xs = new XmlSerializer(typeof(Appointments));
            XmlTextReader reader = new XmlTextReader(FILENAME);
            Appointments newAppointments = (Appointments)xs.Deserialize(reader);

        }
    }
    [XmlRoot("appointments")]
    public class Appointments
    {
        [XmlElement("appointment")]
        public List<Appointment> appointments { get; set; }

    }
    [XmlRoot("appointment")]
    public class Appointment
    {
        [XmlElement("start")]
        public DateTime start { get; set; }
        [XmlElement("length")]
        public int length { get; set; }
        [XmlElement("displayableDescription")]
        public string displayableDescription { get; set; }
        [XmlElement("occursOnDate")]
        public bool occursOnDate { get; set; }
    }


}

答案 1 :(得分:0)

我会使用Json,因为它比XML更清晰,更小。例如:

private IList<IAppointment> _list {get; set;}

public Appointments()
{
    _list = Load() ?? new List<IAppointment>();
}

public List<IAppointment> Load()
{
    try
    {
        var json = File.ReadAllText(".Appointments.json");
        var list = JsonConvert.DeserializeObject<List<IAppointment>>(json);
        return list;
    }
    catch
    {
        return null;
    }
}

public bool Save()
{
    try
    {
        var json = JsonConvert.SerializeObject(_list);
        File.WriteAllText(".Appointments.json",json);
        return true;
    }
    catch
    {
        return false;
    }
}

不要忘记通过Nuget将Newtonsoft.Json添加到您的项目中:

To install Json.NET, run the following command in the Package Manager Console

PM> Install-Package Newtonsoft.Json -Version 6.0.8

答案 2 :(得分:0)

我将代码合并到您的课程中。需要调试,但应该帮助您更好地理解序列化。

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

namespace Calendar
{
    class Program
    {

        static void Main(string[] args)
        {
        }
    }
    public class IAppointments : IAppointment
    {
        public DateTime Start { get; set; }
        public int Length { get; set; }
        public string DisplayableDescription { get; set; }
        public bool OccursOnDate(DateTime date)
        {
            return true;
        }
    }
    class Appointments : IAppointments
    {
        const string FILENAME = @"c:\temp\test.xml";
        private readonly IList<IAppointment> _list = new List<IAppointment>();

        public void Add(IAppointment item)
        {
            _list.Add(item);
        }

        public bool Load()
        {
            XmlSerializer xs = new XmlSerializer(typeof(c_Appointments));
            XmlTextReader reader = new XmlTextReader(FILENAME);
            c_Appointments newAppointments = (c_Appointments)xs.Deserialize(reader);

            foreach (Appointment appointment in newAppointments.appointments)
            {
                IAppointments newAppointment = new IAppointments();
                newAppointment.Start = appointment.start;
                newAppointment.Length = appointment.length;
                newAppointment.DisplayableDescription = appointment.displayableDescription;
                this.Add(newAppointment);
            }

            return true;

        }

        public bool Save()
        {
             c_Appointments appointments = new c_Appointments();
             appointments.appointments = new List<Appointment>();
             foreach (IAppointment iAppointment in _list)
             {
                Appointment  newAppoint = new Appointment();
                appointments.appointments.Add(newAppoint);
                newAppoint = (Appointment)iAppointment;
             }

            XmlSerializer serializer = new XmlSerializer(typeof(c_Appointments));

            StreamWriter writer = new StreamWriter(FILENAME);
            serializer.Serialize(writer, appointments);
            writer.Flush();
            writer.Close();
            writer.Dispose();

            return true;
        }
    }
    public interface IAppointment
    {
        DateTime Start { get; }
        int Length { get; }
        string DisplayableDescription { get; }
        bool OccursOnDate(DateTime date);
    }
    [XmlRoot("appointments")]
    public class c_Appointments
    {
        [XmlElement("appointment")]
        public List<Appointment> appointments { get; set; }

    }
    [XmlRoot("appointment")]
    public class Appointment
    {
        [XmlElement("start")]
        public DateTime start { get; set; }
        [XmlElement("length")]
        public int length { get; set; }
        [XmlElement("displayableDescription")]
        public string displayableDescription { get; set; }
    }

}
​