了解序列化

时间:2015-06-16 00:09:04

标签: c# serialization

上下文

我正在尝试了解如何使用序列化,以前从未使用过它。

现在我的单例对象(Main类)中有一个populate方法,它基本上使用我的addMember方法将一些成员对象添加到成员列表中

我想序列化此成员列表一旦我可以序列化和反序列化列表,我就可以删除我的填充方法。

问题

  • 如何序列化此列表,以便在启动时反序列化成员列表?

  • 我在哪里专门序列化?我在创建新成员时是序列化,还是在关机时序列化列表并在启动时反序列化。

  • 由于可以编辑成员信息,如何序列化更新并覆盖以前保存的数据?

代码列表

我对序列化有点新意,但这是我的代码,我正在使用一种方法,因为我觉得这样更干净,在我的主类中使用ISerializable。这是我的主要课程的一些片段,请记住我的代码中有大量的评论,这就是为什么我之前没有发布这个:

namespace HillRacingGraded
{
    [Serializable]
    public class HillRacing : ISerializable
    {
        /// <summary>
        /// Singleton object hillracing
        /// </summary>
        private static HillRacing hillracing;

        GUIUtility gui = new GUIUtility();


        /// <summary>
        /// Instance property returns the singleton instance
        /// </summary>
        public static HillRacing Instance
        {
            get
            {
                if (hillracing == null)
                    hillracing = new HillRacing();
                return hillracing;
            }
        }

        /// <summary>
        /// public Property that returns races list, can be accessed by other classes.
        /// </summary>
        public List<BaseRace> Races
        {
            get
            {
                return races;
            }
            set
            {
                races = value;
            }
        }
        /// <summary>
        /// public Property that returns members list, can be accessed by other classes.
        /// </summary>
        public List<BaseMember> Members
        {
            get
            {
                return members;
            }
            set
            {
                members = value;
            }
        }

        /// <summary>
        /// instantiate the list of members
        /// </summary>
        private List<BaseMember> members; //I WANT TO SERIALIZE THIS

        /// <summary>
        /// instantiate the list of races
        /// </summary>
        private List<BaseRace> races; //I WANT TO SERIALIZE THIS

        /// <summary>
        /// Default constructor for hillracing.
        /// </summary>
        public HillRacing()
        {
            //members is a new list of the BaseMember objects.
            //races is a new list of the BaseRace objects.


            members = new List<BaseMember>();
            races = new List<BaseRace>();

            //call the populate method on launch, mostly for testing purposes.
            Populate();


        }

        /// <summary>
        /// Hillracing constructor for serialization
        /// </summary>
        /// <param name="info"></param>
        /// <param name="ctxt"></param>
        public HillRacing(SerializationInfo info, StreamingContext ctxt)
        {
             this.members = (List<BaseMember>)info.GetValue("Members", typeof(List<BaseMember>));
             this.races = (List<BaseRace>)info.GetValue("Races", typeof(List<BaseRace>));
        }

        /// <summary>
        /// get object data
        /// </summary>
        /// <param name="info"></param>
        /// <param name="ctxt"></param>
        public void GetObjectData(SerializationInfo info, StreamingContext ctxt)
         {
             info.AddValue("Members", this.members);
         }


        /// <summary>
        ///  Adds a new junior member to the list of all members.
        /// </summary>
        /// <param name="stringfirstname">first name of the member</param>
        /// <param name="stringlastname">last name of the member</param>
        /// <param name="stringmiddlename">middle name of the member</param>
        /// <param name="stringtitle">title of the member</param>
        /// <param name="strst">street of the member</param>
        /// <param name="strtwn">Town of the member</param>
        /// <param name="strpc">Postcode of the member</param>
        /// <param name="strEmail">email of the member</param>
        /// <param name="intMobile">Mobile of the member</param>
        /// <param name="intHome">Home phone of the member</param>
        /// <param name="shrnumber">ID number of the member</param>
        /// <param name="memtype">Type of the member</param>
        /// <param name="username">username of the member</param>
        /// <param name="noracesrun">number of races that the member has run</param>
        /// <param name="perraceswon">percentage of races that the member has won</param>
        /// <param name="mempic">image of the member</param>
        /// <param name="memclub">the club the member is part of</param>
        /// <param name="gender">the gender of the member</param>
        /// <param name="memexp">the experience level the member has</param>
        /// <param name="yearofbirth">the year of birth the member was born in</param>
        /// <param name="monthofbirth">the month of birth the member was born in</param>
        /// <param name="dayofbirth">the day of birth the member was born on</param>
        public void addJunior(string stringfirstname, string stringlastname, string stringmiddlename, string stringtitle, string strst, string strtwn, string strpc, string strEmail, int intMobile, int intHome,
            string shrnumber, string memtype, string username, string password, int noracesrun, float perraceswon, string mempic, string memclub, string gender, int memexp, int yearofbirth, int monthofbirth, int dayofbirth, string nextofkin, string docName, string docTel, string healthIssues, string parentalConsent)
        {

            // create a new member with the entered parameters to add to the list.
            JuniorMember newMember = new JuniorMember(stringfirstname, stringlastname, stringmiddlename, stringtitle, strst, strtwn, strpc, strEmail, intMobile, intHome, shrnumber, memtype, username, password, noracesrun, perraceswon, mempic, memclub, gender, memexp, yearofbirth, monthofbirth, dayofbirth,nextofkin,docName,docTel,healthIssues,parentalConsent);

            //use add functionality of list to add to the list.
            members.Add(newMember);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="stringfirstname">first name of the member</param>
        /// <param name="stringlastname">last name of the member</param>
        /// <param name="stringmiddlename">middle name of the member</param>
        /// <param name="stringtitle">title of the member</param>
        /// <param name="strst">street of the member</param>
        /// <param name="strtwn">Town of the member</param>
        /// <param name="strpc">Postcode of the member</param>
        /// <param name="strEmail">email of the member</param>
        /// <param name="intMobile">Mobile of the member</param>
        /// <param name="intHome">Home phone of the member</param>
        /// <param name="shrnumber">ID number of the member</param>
        /// <param name="memtype">Type of the member</param>
        /// <param name="username">username of the member</param>
        /// <param name="noracesrun">number of races that the member has run</param>
        /// <param name="perraceswon">percentage of races that the member has won</param>
        /// <param name="mempic">image of the member</param>
        /// <param name="memclub">the club the member is part of</param>
        /// <param name="gender">the gender of the member</param>
        /// <param name="memexp">the experience level the member has</param>
        /// <param name="yearofbirth">the year of birth the member was born in</param>
        /// <param name="monthofbirth">the month of birth the member was born in</param>
        /// <param name="dayofbirth">the day of birth the member was born on</param>
        /// <param name="nextofkin">The next family member contact</param>
        /// <param name="docName">The name of the members doctor</param>
        /// <param name="docTel">A telephone number for the doctor</param>
        /// <param name="healthIssues">the health issues this member has.</param>
        public void addSenior(string stringfirstname, string stringlastname, string stringmiddlename, string stringtitle, string strst, string strtwn, string strpc, string strEmail, int intMobile, int intHome,
            string shrnumber, string memtype, string username, string password, int noracesrun, float perraceswon, string mempic, string memclub, string gender, int memexp, int yearofbirth, int monthofbirth, int dayofbirth, string nextofkin, string docName, string docTel, string healthIssues)
        {

            //create a new member with the entered parameters to add to the list.
            SeniorMember newMember = new SeniorMember(stringfirstname, stringlastname, stringmiddlename, stringtitle, strst, strtwn, strpc, strEmail, intMobile, intHome, shrnumber, memtype, username, password, noracesrun, perraceswon, mempic, memclub, gender, memexp, yearofbirth, monthofbirth, dayofbirth,docName,docTel,healthIssues);

            //use standard list functionality of list to add this new member to the list.
            members.Add(newMember);

        }

这是Serializer类中的Serialization方法:

    public void SerializeObject(string filename, object objectToSerialize)
    {
        Stream stream = File.Open(filename + ".bin", FileMode.Create);
        BinaryFormatter bFormatter = new BinaryFormatter();
        bFormatter.Serialize(stream, objectToSerialize);
        stream.Close();
    }

问题是,我不知道如何实际使用它。

还有一个反序列化器:

public HillRacing DeSerializeObject(string filename)
{
    HillRacing hillracing;
    Stream stream = File.Open(filename + ".bin", FileMode.Open);
    BinaryFormatter bFormatter = new BinaryFormatter();
    hillracing = (HillRacing)bFormatter.Deserialize(stream);
    stream.Close();
    return hillracing;
}

1 个答案:

答案 0 :(得分:0)

虽然你已完成了大部分内容,但我建议使用一些小的泛型作为

public static class StreamUtilities
{
    public static T GetObject<T>(Byte[] rawimage) where T : class
    {
        try
        {
            MemoryStream memStream = new MemoryStream();

            BinaryFormatter binForm = new BinaryFormatter();
            memStream.Write(rawimage, 0, rawimage.Length);
            memStream.Seek(0, SeekOrigin.Begin);
            return binForm.Deserialize(memStream) as T;
        }
        catch (Exception ex)
        {
            return null;
        }
    }
    public static  Byte[] Serialize<T>(this T obj) where T:class
    {
        if (obj == null)
            return null;
        BinaryFormatter bf = new BinaryFormatter();
        MemoryStream ms = new MemoryStream();
        bf.Serialize(ms, obj);
        return ms.ToArray();
    }
}

然后在你的主类或者你希望它使用include到命名空间,然后使用上面的扩展方法

Object1 a=new Object1();// any serializable object
serializedbytes=a.Serialize<Object1>();
//deserialize
Object b=StreamUtilities.GetObject<Object1>(serializedbytes);

上述扩展方法将允许对任何可序列化的对象进行序列化/反序列化。

相关问题